ubuntu下使用nginx keepalived 搭建nginx主备

2016/7/15 posted in  linux

ubuntu 下使用nginx keepalived

nginx自身是不带高可用冗余机制的,一般的模式是使用keepalived来进行主备冗余。

nginx安装

首先更新一下apt-get

sudo apt-get update

安装libtool库

安装libtool库和make

    sudo apt-get install make
    sudo apt-get install libtool

安装 openssl

    sudo apt-get install openssl libssl-dev libperl-dev

安装 zlib

    cd /usr/local/src/
    sudo wget http://zlib.net/zlib-1.2.11.tar.gz
    sudo tar -xvf zlib-1.2.11.tar.gz
    cd zlib-1.2.11
    sudo ./configure
    make
    sudo make install

安装pcre

    sudo apt-get install  gcc;
    sudo apt-get install  g++;
    cd /usr/local/src/
    # 已过期sudo wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.38.tar.gz
    wget http://171.64.64.64/pub/exim/pcre/pcre-8.38.tar.gz
    wget https://ftp.pcre.org/pub/pcre/pcre-8.38.tar.gz
    sudo tar -zxvf pcre-8.38.tar.gz
    cd pcre-8.38
    ./configure
    make
    sudo make install

安装 nginx

    cd /usr/local/src/
    # sudo wget http://nginx.org/download/nginx-1.9.3.tar.gz
    c
    sudo tar -xzvf nginx-1.9.3.tar.gz
    cd nginx-1.9.3
    ./configure --user=www-data --group=www-data --with-debug --with-http_gzip_static_module --with-http_ssl_module --with-pcre=../pcre-8.38/ --with-http_perl_module --with-perl=/usr/bin/perl --with-http_stub_status_module --with-http_realip_module --prefix=/usr/local/nginx
    make
    sudo make install
    ./configure  --prefix=/usr/local/nginx --with-pcre --user=www --group=www --with-file-aio  --with-http_ssl_module --with-http_flv_module --with-http_gzip_static_module  --with-http_stub_status_module  --with-cc-opt=' -O3'
安装keepalived-1.2.7

安装keepalived:

    apt-get  install  keepalived
    groupadd  -f  www
    useradd  -g www  www
分别在两台机器上编写配置文件
    vim /usr/local/nginx/conf/nginx.conf

内容如下:

    user  www www;
    worker_processes    1;                    ##启动进程,通常设置为cpu核数
    error_log    logs/error.log    notice;         #全局错误日志及PID文件
    pid                logs/nginx.pid;
    events  {
            worker_connections    1024;  #单个后台worker process进程的最大并发链接数
    }
    #设定http服务器,利用它的反向代理功能提供负载均衡支持
      http  {
            include             mime.types; #设定mime类型,类型由mime.type文件定义
            default_type    application/octet-stream;
    ####sendfile 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,对于####普通应用,必须设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,####以平衡磁盘与网络I/O处理速度,降低系统的uptime.
            sendfile            on;
            tcp_nopush         on;
            keepalive_timeout    65;  #连接超时时间
            gzip    on;  #开启gzip压缩
            server  {
                    listen             80;
                    server_name    localhost;
    location / {
    root  html; ###定义服务器的默认网站根目录位置
    index  index.html index.htm; #定义首页索引文件的名称
    }
        error_page     500 502 503 504    /50x.html;
        location = /50x.html  {
            root     html;
                     index     index.html index.htm;
                    }
            }
    }
分别在两台机器上创建测试文件

如果在_usr_local_ng inx_conf_nginx.conf不改的话,nginx的默认root为_usr_local_nginx_html_

    echo "192.168.0.115" > /usr/local/nginx/html/index.html  ##在server1上
    echo "192.168.0.110" > /usr/local/nginx/html/index.html  ##在server2上
在server1 上编辑配置文件(每一个“{”的前面都有一个空格)

这里应该写在 _etc_keepalived_keepalived.conf中,keepalived会自动的去搜索_etc/keepalived目录下面的所有配置文件

vim  /etc/keepalived.c

内容如下(内容中的路径必须都为绝对路径):

    vrrp_script chk_http_port  {
                    script "/opt/nginx_pid.sh"         ###监控脚本
                    interval 2                      ###监控时间
                    weight 2                       ###权值
    }
    global_defs  {
    notification_email  {
    123@163.com                    #警告邮箱
    }
    notification_email_from  123@163.com
    smtp_server 127.0.0.1
    smtp_connect_timeout 30
    router_id  LVS_Twioo
    }
    vrrp_instance VI_1  {
            state MASTER                        ### 设置为主机
            interface eth0                         ### 监控网卡
            virtual_router_id 51                    ### 这个两台服务器必须一样
            priority 101                    ### 权重值 MASTRE 一定要高于 BAUCKUP
                                      ###有的地方说是至少要比BACKUP高50
            authentication  {
                     auth_type PASS             ### 加密
                     auth_pass eric              ### 加密的密码,两台服务器一定要一样, 不然会出错
            }
            track_script  {
                    chk_http_port                   ### 执行监控的服务
            }
            virtual_ipaddress  {
                 192.168.0.222                      ###    VIP 地址
            }
    }
在server2 上编辑配置文件(每一个“{”的前面都有一个空格)
    vrrp_script chk_http_port  {
                    script "/opt/nginx_pid.sh"         ###监控脚本
                    interval 2                      ###监控时间
                    weight 2                       ###目前搞不清楚
    }
    global_defs  {
    notification_email  {
    123@163.com                    ###警告邮箱
    }
    notification_emali_from  123@163.com
    smtp_server  127.0.0.1
    smtp_connect_timeout  30
    router_id  LVS_twioo
    }
    vrrp_instance VI_1  {
            state BACKUP                        ### 设置为备机
            interface eth0                         ### 监控网卡
            virtual_router_id 51                    ### 这个两台服务器必须一样
            priority 50                   ### 权重值BAUCKUP一定要低于MASTER
            authentication  {
                  auth_type PASS             ### 加密
                  auth_pass eric               ### 加密的密码,两台服务器一定要 一样,不然会出错
            }
            track_script  {
                 chk_http_port                   ### 执行监控的服务
            }
            virtual_ipaddress  {
                 192.168.0.222                      ###    VIP 地址
            }
    }
编辑nginx监控脚本
    vim  /opt/nginx_pid.sh

内容如下:

    #!/bin/bash     
    #varsion 1.0
    A=`ps -C nginx --no-header |wc -l`      
    if [ $A -eq 0 ];then        
           /usr/local/nginx/sbin/nginx      
           sleep 3      
           if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
                 killall keepalived     
           fi       
    fi

注意:在写脚本的时候,“[ ]”的前后都要有空格

然后给脚本加上执行权限:# chmod 755 nginx_pid.sh

这是一个监控脚本,放在Nginx机器上(因为目前主要是由它提供服务),每隔3秒执行一次,用ps -C 命令来收集nginx的PID值到底是否为0,如果是0的话(即Nginx进程死掉了),尝试启动nginx进程;如果继续为0,即nginx启动失改,则关闭本机的Keeplaived进程,VIP地址则会由备机接管,当然了,整个网站就会由备机的Nginx来提供服务了,这样保证Nginx进程的高可用。

分别在两个服务器启动nginx 和 keepalived
    # /usr/local/nginx/sbin/nginx            ##启动nginx
    # /etc/init.d/keepalived  restart /stop/start   ##重启keepalived/停止/启动
    # service  keepalived  restart/stop/start
测试

服务都起来之后,在MASTER和BACKUP上分别指向如下命令:

    ip  a

就会看到虚拟ip在MASTER上绑定了

浏览器中可以访问192.168.0.222,就可以访问到MASTER的页面

然后停掉主机的nginx(# killall nginx),如果nginx没有故障,keepalived就会尝试重新启动nginx服务。如果nginx发生故障,无法重新启动,那么就会自动切换到备机上,如果在用192.168.0.222访问的话,就会访问到BACKUP的页面(用# ip a 命令查看,虚拟ip绑定在BACKUP上)

当MASTER修复好后,需要手动启动keepalived 程序,以便将服务重新切换回主服务器。

操作中出现的错误:

1、缺少pcre 库

    ./configure: error: the HTTP rewrite module requires the PCRE library. You can either disable the module by using --without-http_rewrite_module option, or install the PCRE library into the system, or build the PCRE library statically from the source with nginx by using --with-pcre=<path> option.

详细出处参考:http://www.jb51.net/os/Ubuntu/64596.html需要安装pcre库,按照上面方法安装即可

2、缺少openssl包

    ./configure: error: the HTTP cache module requires md5 functions
    from OpenSSL library. You can either disable the module by using
    --without-http-cache option, or install the OpenSSL library into the system,
    or build the OpenSSL library statically from the source with nginx by using
    --with-http_ssl_module --with-openssl=<path> options.

详细出处参考:http://www.jb51.net/os/Ubuntu/64596.html需要安装openssl包

3、缺少用户

    nginx: [emerg] getpwnam(“www”) failed

错误的原因是没有创建www这个用户,应该在服务器系统中添加www用户组和用户www

4、缺少编译器错误

    libtool: compile: unrecognized option `-DHAVE_CONFIG_H'
    libtool: compile: Try `libtool --help' for more information.
    make[1]: *** [pcrecpp.lo] Error 1
    make[1]: Leaving directory `/usr/local/src//pcre-8.31'
    make: *** [all] Error 2root@wolfdog-virtual-machine:~/work/pcre-8.12$ libtool -help -DHAVE_CONFIG_H
    The program 'libtool' is currently not installed. You can install it by typing:
    sudo apt-get install libtool

缺少g++编译器、缺少libtool包

5、缺少zlib库,需要安装zlib库

./configure: error: the HTTP gzip module requires the zlib library.

You can either disable the module by using --without-http_gzip_module

option, or install the zlib library into the system, or build the zlib library

statically from the source with nginx by using --with-zlib= option.

参考文章:

http://deidara.blog.51cto.com/400447/302402/

http://hi.baidu.com/cong_rong520/item/ca18c07d6f4413356f29f65c

http://baobeituping.iteye.com/blog/911509