资讯专栏INFORMATION COLUMN

nginx 负载均衡搭建

endiat / 1121人阅读

摘要:客户请求头缓冲大小默认会用这个来读取值,如果设定通过上传文件的大小磁盘和之间互相拷贝数据或任意两个文件描述符。

环境说明

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文件

#! /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 服务

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/30370.html

相关文章

  • 使用Nginx反向代理和负载均衡搭建多人测试环境

    摘要:反向代理和负载均衡通过判断不同的,我们可以通过反向代理转发到不同的机器和端口,这里同一台测试机可以转发到本机的不同的端口,监听不同的端口设置不同的网站目录。 showImg(https://segmentfault.com/img/bVG4E4?w=1328&h=874); 假如我们使用 git 进行版本控制,在一个大型网站中,开发人员在不同的分支上开发不同的需求,当一个需求开发完成需...

    DDreach 评论0 收藏0
  • React搭建个人博客(二)consul-template+nginx+docker实现负载均衡

    摘要:前两个数据业务相关的服务即下图的,第三个项目就是的实现的负载均衡。这里后台,前台项目各启动了三个实例,用户访问的时候,就会根据配置的负载均衡的策略,访问其中一个。这一部分与之前我转发的实现服务发现及网关其实也只是差了个网关和负载均衡。 一.简介 上一篇只讲了博客的前端问题,这一篇讲一下后端的微服务搭建。项目的后端使用的thinkjs框架,在我之前的博客中已经写过,这里就不重点说明了。后...

    Coding01 评论0 收藏0
  • Nginx+Redis实现session共享的均衡负载

    摘要:于是乎,,,搜到最多的词就是均衡负载,搭配的一般都是。回头再看看,先换个浏览器首次访问再次访问带上首次访问带上再次次访问可见的确是达到了均衡负载同时共享的目的。 前言 大学三年多,也做个几个网站和APP后端,老是被人问到,如果用户多了服务器会不会挂,总是很尴尬的回答:哈哈,我们的用户还少,到了服务器撑不住的时候,估计都上市了吧。说是这么说,但是对于有强迫症的我,这个问题一直回响在我脑海...

    ZHAO_ 评论0 收藏0

发表评论

0条评论

endiat

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<