nginx 負載均衡搭建

環境說明

192.168.1.208    Nginx負載服務器
192.168.1.210    webA服務器 PHP memcache xcache mysql
192.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

# 源碼包安裝libiconv
tar zxvf libiconv-1.14.tar.gz
cd libiconv-1.14/
./configure --prefix=/usr/local/libiconv
make
make install

# 源碼包安裝libiconv
tar zxvf libmcrypt-2.5.8.tar.gz
cd libmcrypt-2.5.8/
./configure --prefix=/usr/local/libmcrypt/
make
make install

# 開始編譯PHP
tar -zxvf php-5.6.3.tar.gz
cd 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 \

# 安裝配置
make
make install

配置php-fpm.conf文件

cp php.ini-production  /usr/local/php/etc/php.ini

# 添加用戶和用戶組
[root@admin local]# groupadd  www  #添加www組
[root@admin local]# useradd -g  www www -s /bin/false  // 不容許www用戶直接登陸系統

# 拷貝模板文件爲php-fpm配置文件
cp /usr/local/php/etc/php-fpm.conf.default /usr/local/php/etc/php-fpm.conf
vi /usr/local/php/etc/php-fpm.conf     // 編輯
user = www                             // 設置php-fpm運行帳號爲www  默認帳號爲nginx
group = www                            // 設置php-fpm運行組爲www
pid = run/php-fpm.pid                  // 取消前面的分號
listen = 127.0.0.1:9000 改 listen = 0.0.0.0:9000


# 開啓opcache緩存
vim /usr/local/php/etc/php.ini
  
[opcache]
zend_extension=opcache.so
opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=2018
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=20000
opcache.revalidate_freq=10
opcache.fast_shutdown=1
opcache.optimization_level=1
;opcache.max_wasted_percentage=5
;opcache.use_cwd=1
;opcache.validate_timestamps=1
;opcache.revalidate_path=0
;opcache.save_comments=1
;opcache.load_comments=1
;opcache.enable_file_override=0
;opcache.inherited_hack=1
;opcache.dups_fix=0
;opcache.blacklist_filename=
;opcache.max_file_size=0
;opcache.consistency_checks=0
;opcache.force_restart_timeout=180
;opcache.error_log=
;opcache.log_verbosity_level=1
;opcache.preferred_memory_model=
;opcache.protect_memory=0


# 保存退出
:wq!

php-fpm開機自啓動配置

#! /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/php
exec_prefix=${prefix}
 
php_fpm_BIN=${exec_prefix}/sbin/php-fpm
php_fpm_CONF=${prefix}/etc/php-fpm.conf
php_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 -y
yum install libselinux krb5-libs libcom_err-devel libsepol-devel libselinux-devel e2fsprogs-libs libss keyutils-libs-devel krb5-devel e2fsprogs libselinux-utils -y
yum -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.gz
cd /usr/local/src
mkdir /usr/local/pcre                  // 建立安裝目錄
tar  zxvf pcre-8.30.tar.gz
cd pcre-8.30
./configure  --prefix=/usr/local/pcre  // 配置
make
make 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.gz
tar -zxf /data/soft/nginx/nginx-1.8.1.tar.gz
cd /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 \
make
make install

# nginx安裝第三方擴展
tar -zxf /data/soft/nginx/ngx_http_accounting_module-master.tar.gz
cp -rf ngx_http_accounting_module-master /usr/local/
# 切換到nginx源碼包目錄執行
./configure --prefix=/usr/local/nginx --add-module=/usr/local/ngx_http_accounting_module-master/
make
make 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
#variables
NGINX_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=$1
prog=nginx
#load system function
. /etc/rc.d/init.d/functions
#function:echo ok or error
function if_no {
if [ $2 == 0 ]; then
echo -n $"$1 ${prog}:" && success && echo
else
echo -n $"$1 ${prog}:" && failure && echo
fi
}
#start nginx
function start {
rm -f ${NGINX_PID} 2>/dev/null
if [ -s ${NGINX_PID} ]; then
echo "nginx already running" 
else
if [ `${NETSTAT} -tnpl | grep nginx | wc -l` -eq 0 ]; then
rm -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 $?
fi
fi
}
#stp nginx
function stop {
if [ -s ${NGINX_PID} ]; then
cat ${NGINX_PID} | xargs kill -QUIT
if_no stop $?
else
        if [ `${NETSTAT} -tnpl | grep nginx | wc -l` -eq 0 ]; then
rm -f ${NGINX_PID} 2>/dev/null
if_no stop 0
else
rm -f ${NGINX_PID} 2>/dev/null
kill `${NETSTAT} -tnpl | grep nginx | awk '{ print $7}' | cut -d '/' -f 1`
if_no stop $?
fi
fi
}
function restart {
if [ -s ${NGINX_PID} ]; then
cat ${NGINX_PID} | xargs kill -HUP
if_no restart $?
else
stop
sleep 1
start
fi
}
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 in
start)
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       // 重啓nginx
chkconfig --add nginx
chkconfig --level 2345 nginx on

# 重啓服務器
/etc/init.d/nginx stop         # 中止nginx 服務
/etc/init.d/nginx start        # 啓動nginx 服務

如下擴展配置自行安裝使用

AB測試與centos系統優化 

ab測試與centos優化地址javascript

配置Memcache緩存

Memcache配置地址php

配置Xcache代碼緩存

xcache緩存配置地址css

相關文章
相關標籤/搜索