博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
nginx 负载均衡搭建
阅读量:6971 次
发布时间:2019-06-27

本文共 13258 字,大约阅读时间需要 44 分钟。

环境说明

192.168.1.208    Nginx负载服务器192.168.1.210    webA服务器 PHP memcache xcache mysql192.168.1.211    webB服务器 PHP memcache xcache

webA/webB 服务器PHP环境配置

# 注意:freetype在生成验证码图片需要用,所以必须要安装的[root@iZ23g4snm6gZ soft]# yum install openssl-devel  libxml2 libxml2-devel curl-devel  libevent[root@iZ23g4snm6gZ soft]# yum install libpng libpng-devel libjpeg libjpeg-devel freetype-devel gd gd-devel mysql-devel# 源码包安装libiconvtar zxvf libiconv-1.14.tar.gzcd libiconv-1.14/./configure --prefix=/usr/local/libiconvmakemake install# 源码包安装libiconvtar zxvf libmcrypt-2.5.8.tar.gzcd libmcrypt-2.5.8/./configure --prefix=/usr/local/libmcrypt/makemake install# 开始编译PHPtar -zxvf php-5.6.3.tar.gzcd php-5.6.3./configure --prefix=/usr/local/php/ \--with-config-file-path=/usr/local/php/etc/ \--enable-fpm \--with-fpm-user=nginx \--with-fpm-group=nginx \--with-zlib \--with-libxml-dir \--enable-sockets \--with-curl \--with-jpeg-dir \--with-png-dir \--with-gd \--with-iconv-dir=/usr/local/libiconv \--with-freetype-dir= \--enable-gd-native-ttf \--with-xmlrpc \--with-openssl \--with-mhash \ --with-mcrypt=/usr/local/libmcrypt/ \--with-pear \--enable-mbstring \--enable-sysvshm \--enable-zip \--with-mysql \--with-mysqli \--with-mysql-sock \--with-pdo-mysql \--disable-fileinfo \# 安装配置makemake install

配置php-fpm.conf文件

#! /bin/sh ### BEGIN INIT INFO# Provides:          php-fpm# Required-Start:    $remote_fs $network# Required-Stop:     $remote_fs $network# Default-Start:     2 3 4 5# Default-Stop:      0 1 6# Short-Description: starts php-fpm# Description:       starts the PHP FastCGI Process Manager daemon### END INIT INFO prefix=/usr/local/phpexec_prefix=${prefix} php_fpm_BIN=${exec_prefix}/sbin/php-fpmphp_fpm_CONF=${prefix}/etc/php-fpm.confphp_fpm_PID=${prefix}/var/run/php-fpm.pid php_opts="--fpm-config $php_fpm_CONF" wait_for_pid () {    try=0     while test $try -lt 35 ; do         case "$1" in            'created')            if [ -f "$2" ] ; then                try=''                break            fi            ;;             'removed')            if [ ! -f "$2" ] ; then                try=''                break            fi            ;;        esac         echo -n .        try=`expr $try + 1`        sleep 1     done } case "$1" in    start)        echo -n "Starting php-fpm "         $php_fpm_BIN $php_opts         if [ "$?" != 0 ] ; then            echo " failed"            exit 1        fi         wait_for_pid created $php_fpm_PID         if [ -n "$try" ] ; then            echo " failed"            exit 1        else            echo " done"        fi    ;;     stop)        echo -n "Gracefully shutting down php-fpm "         if [ ! -r $php_fpm_PID ] ; then            echo "warning, no pid file found - php-fpm is not running ?"            exit 1        fi         kill -QUIT `cat $php_fpm_PID`         wait_for_pid removed $php_fpm_PID         if [ -n "$try" ] ; then            echo " failed. Use force-quit"            exit 1        else            echo " done"        fi    ;;     force-quit)        echo -n "Terminating php-fpm "         if [ ! -r $php_fpm_PID ] ; then            echo "warning, no pid file found - php-fpm is not running ?"            exit 1        fi         kill -TERM `cat $php_fpm_PID`         wait_for_pid removed $php_fpm_PID         if [ -n "$try" ] ; then            echo " failed"            exit 1        else            echo " done"        fi    ;;     restart)        $0 stop        $0 start    ;;     reload)         echo -n "Reload service php-fpm "         if [ ! -r $php_fpm_PID ] ; then            echo "warning, no pid file found - php-fpm is not running ?"            exit 1        fi         kill -USR2 `cat $php_fpm_PID`         echo " done"    ;;     *)        echo "Usage: $0 {start|stop|force-quit|restart|reload}"        exit 1    ;; esac# 开机自启动配置mv php-fpm /etc/init.d/               // 移动php-fpm脚本到init.d目录下chmod a+x /etc/init.d/php-fpm         // 添加执行权限chkconfig --add php-fpm               // 添加开机启动配置chkconfig --level 2345 php-fpm on     // 配置开机启动权限级别

Nginx 服务器配置安装

# 扩展包安装yum install libcom_err pkgconfig -yyum install libselinux krb5-libs libcom_err-devel libsepol-devel libselinux-devel e2fsprogs-libs libss keyutils-libs-devel krb5-devel e2fsprogs libselinux-utils -yyum -y install zlib zlib-devel openssl openssl-devel make gcc gcc-c++ ncurses-devel pcre-devel# 安装Nginx# 安装pcre (支持nginx伪静态)ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.30.tar.gzcd /usr/local/srcmkdir /usr/local/pcre                  // 创建安装目录tar  zxvf pcre-8.30.tar.gzcd pcre-8.30./configure  --prefix=/usr/local/pcre  // 配置makemake install# 安装Nginx[root@admin local]# groupadd  www  #添加www组[root@admin local]# useradd -g  www www -s /bin/false  // 不允许www用户直接登录系统wget http://nginx.org/download/nginx-1.8.1.tar.gztar -zxf /data/soft/nginx/nginx-1.8.1.tar.gzcd /data/soft/nginx/nginx-1.8.1# 开始配置Nginx./configure --prefix=/usr/local/nginx \--with-pcre \--with-http_ssl_module \--with-http_realip_module \--with-http_addition_module \--with-http_sub_module \--with-http_dav_module \--with-http_flv_module \--with-http_mp4_module \--with-http_gzip_static_module \--with-http_random_index_module \--with-http_secure_link_module \--with-http_degradation_module \--with-http_stub_status_module \--with-ipv6 \--with-mail \--with-mail_ssl_module \--conf-path=/usr/local/nginx/conf/nginx.conf \--group=wwww \--user=www \--error-log-path=/usr/local/nginx/logs/error.log \--http-log-path=/usr/local/nginx/logs/access.log \--pid-path=/usr/local/nginx/logs/nginx.pid \--lock-path=/usr/local/nginx/logs/lock.txt \makemake install# nginx安装第三方扩展tar -zxf /data/soft/nginx/ngx_http_accounting_module-master.tar.gzcp -rf ngx_http_accounting_module-master /usr/local/# 切换到nginx源码包目录执行./configure --prefix=/usr/local/nginx --add-module=/usr/local/ngx_http_accounting_module-master/makemake install

配置nginx支持php

#user  nobody;user www www;worker_processes       auto;# ginx要开启的进程数 一般等于cpu的总核数,没必要开那么多,1个nginx内存消耗10兆左右#worker_processes       4;# 为每个进程分配cpu,上例中将4 个进程分配到4个cpu,当然可以写多个,或者将一 个进程分配到多个cpu#worker_cpu_affinity    00000001 00000010 00000100 00001000;# 开启nginx错误日志error_log  logs/error.log;#error_log  logs/error.log  notice;#error_log  logs/error.log  info;pid        logs/nginx.pid;# 每个nginx进程打开文件描述符最大数目 配置要和系统的单进程打开文件数一# 致,linux 2.6内核下开启文件打开数为65535,worker_rlimit_nofile就相应,应该填写65535  # nginx调度时分配请求到进程并不是那么的均衡,假如超过会返回502错误。我这里写的大一点worker_rlimit_nofile   819200;events {    # 设置用于复用客户端线程的轮询方法。如果你使用Linux 2.6+,你应该使用epoll。    # 如果你使用*BSD,你应该使用kqueue。    # 值得注意的是如果你不知道Nginx该使用哪种轮询方法的话,它会选择一个最适合你操作系统的    use                            epoll;    # 每个工作进程允许最大的同时连接数(Maxclient = work_processes * worker_connections)    # 默认1024    worker_connections             40960;}http {    # 打开accunting日志分析    http_accounting                on;    http_accounting_name           "JGsrv";    http_accounting_time           30;    # 文件头信息    include       mime.types;    # 默认类型    default_type  application/octet-stream;    # 限制连接模块    limit_req_zone $binary_remote_addr zone=allips:10m rate=20r/s;    # 保存服务器名字的hash表是由指令server_names_hash_max_size 和server_names_hash_bucket_size所控制的。    # 参数hash bucket size总是等于hash表的大小,并且是一路处理器缓存大小的倍数    server_names_hash_bucket_size  128;    # 客户端请求头部的缓冲区大小,这个可以根据你的系统分页大小来设置,    # 一般一个请求的头部大小不会超过1k,不过由于一般系统分页都要大于1k,    # 所以这里设置为分页大小。分页大小可以用命令getconf PAGESIZE取得。    client_header_buffer_size      32k;    # 客户请求头缓冲大小    # nginx默认会用client_header_buffer_size这个buffer来读取header值,如果    large_client_header_buffers    4 32k;    # 设定通过nginx上传文件的大小    client_max_body_size           64m;    # 磁盘和TCP socket之间互相拷贝数据(或任意两个文件描述符)。    # Pre-sendfile是传送数据之前在用户空间申请数据缓冲区    sendfile                       on;    # 告诉nginx在一个数据包里发送所有头文件,而不一个接一个的发送    tcp_nopush                     on;        # 告诉nginx不要缓存数据,而是一段一段的发送,    # 当需要及时发送数据时,就应该给应用设置这个属性,这样发送一小块数据信息时就不能立即得到返回值。    tcp_nodelay                    on;    # 并不会让nginx执行的速度更快,但它可以关闭在错误页面中的nginx版本数字,这样对于安全性是有好处的    server_tokens                  off;    # keepalive超时时间    keepalive_timeout              65;    # 优化fastcgi    fastcgi_connect_timeout        120;    fastcgi_send_timeout           120;    fastcgi_read_timeout           120;    fastcgi_buffer_size            64k;    fastcgi_buffers                4 64k;    fastcgi_busy_buffers_size      128k;    fastcgi_temp_file_write_size   128k;    fastcgi_intercept_errors       on;    # 开启gzip压缩    gzip                           on;    # 默认值: 0 ,不管页面多大都压缩    gzip_min_length                1k;    # 设置系统获取几个单位的缓存用于存储gzip的压缩结果数据流    # 例如 4 4k 代表以4k为单位,按照原始数据大小以4k为单位的4倍申请内存    gzip_buffers                   4 16k;    gzip_http_version              1.0;    gzip_comp_level                2;    gzip_types                     text/plain application/x-javascript text/css application/xml;    gzip_vary                      on;    # 这个将为打开文件指定缓存,默认是没有启用的,max 指定缓存数量,建议和打开文件数一致,    # inactive 是指经过多长时间文件没被请求后删除缓存#    open_file_cache                max=409600 inactive=10s;    # 这个是指多长时间检查一次缓存的有效信息#    open_file_cache_valid          5s;    # open_file_cache 指令中的inactive 参数时间内文件的最少使用次数,    # 如果超过这个数字,文件描述符一直是在缓存中打开的,    # 如上例,如果有一个文件在inactive 时间内一次没被使用,它将被移除#    open_file_cache_min_uses       2;    log_format access_logs '$upstream_response_time $request_time $status $body_bytes_sent $remote_addr $time_local "$http_user_agent" "$request" "$http_referer" "$http_x_forwarded_for"';    # Nginx负载均衡配置    upstream phpServer{        # 服务器内网地址,weight:权重,负载越大   max_fails:允许请求失败的次数   fail_timeout:次失败后,暂停的时间        server 172.20.17.210:9000 weight=1 max_fails=2 fail_timeout=3;        server 172.20.17.211:9000 weight=1 max_fails=2 fail_timeout=3;    }    # 配置虚拟主机,过个server就复制多个    include vhost/*.conf;}

Vhost目录下的虚拟机配置文件

server {    listen       80;    server_name  jt018.com www.jt018.com;    root   /data/www/jt018.com/;    #access_log  logs/host.access.log  main;    # 配置域名重定向    #if ($host != 'www.jt018.com' ) {    #    rewrite ^/(.*)$ http://www.yphp.cn/$1 permanent;    #}    location / {        # 配置rewrite        if (!-e $request_filename) {            rewrite  ^(.*)$  /index.php?$1  last;            break;        }        # include  /usr/local/nginx/html/yphp/.htaccess;        # rewrite ^/(.+)/(.+)[/]?$ /index.php?m=$1&a=$2 last;        # 配置默认访问文件        index  index.php index.html index.htm;    }    # 静态文件缓存30天    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$    {        expires 30d;        # access_log off;    }        # js,css文件缓存15个小时    location ~ .*\.(js|css)?$    {        expires 15d;        # access_log off;    }    #error_page  404              /404.html;    # redirect server error pages to the static page /50x.html    #    error_page   500 502 503 504  /50x.html;    #location = /50x.html {    #    root   html;    #}    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000    #    location ~ \.php$ {        #fastcgi_pass   127.0.0.1:9000;        fastcgi_index  index.php;        fastcgi_intercept_errors on;        fastcgi_pass   phpServer;    # 修改为upstream定义的名称        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;        include        fastcgi_params;    }}

Nginx 开机启动配置

#!/bin/bash# nginx     This shell script takes care of starting and stopping#           nginx## chkconfig: - 13 68# description: nginx is a web server### BEGIN INIT INFO# Provides: $named# Short-Description: start|stop|status|restart|configtest ### END INIT INFO#variablesNGINX_BIN="/usr/local/nginx/sbin/nginx"NGINX_CONF="/usr/local/nginx/conf/nginx.conf"NGINX_PID="/usr/local/nginx/logs/nginx.pid"NETSTAT="/bin/netstat"alter=$1prog=nginx#load system function. /etc/rc.d/init.d/functions#function:echo ok or errorfunction if_no {if [ $2 == 0 ]; thenecho -n $"$1 ${prog}:" && success && echoelseecho -n $"$1 ${prog}:" && failure && echofi}#start nginxfunction start {rm -f ${NGINX_PID} 2>/dev/nullif [ -s ${NGINX_PID} ]; thenecho "nginx already running" elseif [ `${NETSTAT} -tnpl | grep nginx | wc -l` -eq 0 ]; thenrm -f ${NGINX_PID} 2>/dev/null${NGINX_BIN} -c ${NGINX_CONF} if_no start $?        else${NETSTAT} -tnpl | grep nginx | awk '{ print $7}' | cut -d '/' -f 1 > ${NGINX_PID}if_no start $?fifi}#stp nginxfunction stop {if [ -s ${NGINX_PID} ]; thencat ${NGINX_PID} | xargs kill -QUITif_no stop $?else        if [ `${NETSTAT} -tnpl | grep nginx | wc -l` -eq 0 ]; thenrm -f ${NGINX_PID} 2>/dev/nullif_no stop 0elserm -f ${NGINX_PID} 2>/dev/nullkill `${NETSTAT} -tnpl | grep nginx | awk '{ print $7}' | cut -d '/' -f 1`if_no stop $?fifi}function restart {if [ -s ${NGINX_PID} ]; thencat ${NGINX_PID} | xargs kill -HUPif_no restart $?elsestopsleep 1startfi}function status {${NETSTAT} -tnpl | grep nginx | grep LISTEN[ $? == 0 ] && echo "nginx is running" || echo "nginx is not running"}function configtest {${NGINX_BIN} -t}case $alter instart)start;;stop)stop;;restart)restart;;status)status;;configtest)configtest;;*)echo "use:${NGINX} {start|stop|restart|status|configtest}";;esac# 配置Nginx自启动脚本chmod +x /etc/init.d/nginx/etc/init.d/nginx start 或 service nginx start         // 启动nginx/etc/init.d/nginx stop 或 service nginx stop          // 关闭nginx/etc/init.d/nginx restart 或 service nginx restart       // 重启nginxchkconfig --add nginxchkconfig --level 2345 nginx on# 重启服务器/etc/init.d/nginx stop         # 停止nginx 服务/etc/init.d/nginx start        # 启动nginx 服务

转载地址:http://vbosl.baihongyu.com/

你可能感兴趣的文章
Lind.DDD.SSO单点登陆组件的使用(原创)
查看>>
图的创建——邻接表法
查看>>
OJ错误命令解释
查看>>
Javascript的匿名函数
查看>>
python-memcached学习笔记
查看>>
最受美国年轻用户青睐的App排行榜
查看>>
C# 使用 iTextSharp 将 PDF 转换成 TXT 文本
查看>>
初学 Python(十一)——切片
查看>>
lower_bound
查看>>
Python_基础_(正表达式)
查看>>
C++字符串的输入
查看>>
Scrapy安装报错
查看>>
github开源文章生成pdf
查看>>
JavaEE(24) - JAAS开发安全的应用
查看>>
DDD领域驱动设计基本理论知识总结
查看>>
Python操作Redis数据库
查看>>
equals() 和 hashCode()
查看>>
<原创>在PE最后一节中插入补丁程序(附代码)
查看>>
简单的随笔 ,WSDL工具,Oracle备份还原,java调用.net webservice
查看>>
Workman websocket 握手连接
查看>>