nginx+keepalived构建负载均衡代理服务器

一、拓扑图

wKiom1QdJM-Rf88QAAGTyyUuHxw487.jpg

        Nginx有很强代理功能,但是一台nginx就形成了单点,现在使用keepalived来解决这个问题,keepalived的故障转移时间很短.

    Nginx+keepalived双机实现nginx反向代理服务的高可用,一台nginx挂掉之后不影响应用也不影响内网访问外网.

        Master和Backup两边都开启nginx服务,无论Master还是Backup,当其中的一个keepalived服务停止后,vip都会漂移到keepalived服务还在的节点上。


二、安装Nginx和keepalived服务

 1、分别在nginx-master安装nginx  

   [root@90sec src]# yum -y install gcc gcc-c++ openssl-devel pcre-devel automake autoconf 

   [root@90sec src]# groupadd -r nginx

   [root@90sec src]# useradd -r -g nginx nginx

   [root@90sec src]# tar xf nginx-1.7.5.tar.gz 

   [root@90sec src]# cd nginx-1.7.5

   [root@90sec nginx-1.7.5]# ./configure --user=nginx --group=nginx --prefix=/usr/local/nginx --with-http_stub_status_module --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --with-http_gzip_static_module --with-http_flv_module --with-http_mp4_module | tee /tmp/nginx.txt        ###可以把nginx安装的路径保存到nginx.txt中

    [root@90sec nginx-1.7.5]# make && make install

    [root@90sec nginx-1.7.5]# vim /etc/rc.d/init.d/nginx

    

        #!/bin/sh

        #

        # nginx - this script starts and stops the nginx daemon

        #

        # chkconfig:   - 85 15 

        # description:  Nginx is an HTTP(S) server, HTTP(S) reverse \

        #               proxy and IMAP/POP3 proxy server

        # processname: nginx

        # config:      /etc/nginx/nginx.conf

        # config:      /etc/sysconfig/nginx

        # pidfile:     /var/run/nginx.pid

        

        # Source function library.

        . /etc/rc.d/init.d/functions

        

        # Source networking configuration.

        . /etc/sysconfig/network

        

        # Check that networking is up.

        [ "$NETWORKING" = "no" ] && exit 0

        

        nginx="/usr/local/nginx/sbin/nginx"

        prog=$(basename $nginx)

        

        NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf"

        

        [ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx

        

        lockfile=/var/lock/subsys/nginx

        

        make_dirs() {

           # make required directories

           user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`

           options=`$nginx -V 2>&1 | grep 'configure arguments:'`

           for opt in $options; do

               if [ `echo $opt | grep '.*-temp-path'` ]; then

                   value=`echo $opt | cut -d "=" -f 2`

                   if [ ! -d "$value" ]; then

                       # echo "creating" $value

                       mkdir -p $value && chown -R $user $value

                   fi

               fi

           done

        }

        

        start() {

            [ -x $nginx ] || exit 5

            [ -f $NGINX_CONF_FILE ] || exit 6

            make_dirs

            echo -n $"Starting $prog: "

            daemon $nginx -c $NGINX_CONF_FILE

            retval=$?

            echo

            [ $retval -eq 0 ] && touch $lockfile

            return $retval

        }

        

        stop() {

            echo -n $"Stopping $prog: "

            killproc $prog -QUIT

            retval=$?

            echo

            [ $retval -eq 0 ] && rm -f $lockfile

            return $retval

        }

        

        restart() {

            configtest || return $?

            stop

            sleep 1

            start

        }

        

        reload() {

            configtest || return $?

            echo -n $"Reloading $prog: "

            killproc $nginx -HUP

            RETVAL=$?

            echo

        }

        

        force_reload() {

            restart

        }

        

        configtest() {

          $nginx -t -c $NGINX_CONF_FILE

        }

        

        rh_status() {

            status $prog

        }

        

        rh_status_q() {

            rh_status >/dev/null 2>&1

        }

        

        case "$1" in

            start)

                rh_status_q && exit 0

                $1

                ;;

            stop)

                rh_status_q || exit 0

            restart|configtest)

                $1

                ;;

            reload)

                rh_status_q || exit 7

                $1

                ;;

            force-reload)

                force_reload

                ;;

            status)

                rh_status

                ;;

            condrestart|try-restart)

                rh_status_q || exit 0

                    ;;

            *)

                echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"

                exit 2

        esac

                     

    [root@90sec nginx-1.7.5]# chmod +x /etc/rc.d/init.d/nginx

    [root@90sec nginx-1.7.5]# chkconfig --add nginx 

    [root@90sec nginx-1.7.5]# chkconfig nginx on

    [root@90sec nginx-1.7.5]# service nginx restart

    [root@90sec nginx-1.7.5]# ss -anptl | grep "nginx"

LISTEN     0      128                       *:80                       *:*      users:(("nginx",38972,6),("nginx",38973,6))

    [root@90sec nginx-1.7.5]# service nginx status

        nginx (pid 38973 38972) is running...

2、分别创建网站首页

[root@90sec nginx-1.7.5]# echo "Welcom to nginx-master" > /usr/local/nginx/html/index.html

[root@90sec nginx-1.7.5]# curl http://192.168.83.132

        Welcom to nginx-master 

[root@80sec nginx-1.7.5]# echo "Welcome to nginx-backup" > /usr/local/nginx/html/index.html

[root@80sec nginx-1.7.5]# curl http://192.168.83.133

        Welcome to nginx-backup

3、安装keepalived

[root@90sec src]# tar xf keepalived-1.2.12.tar.gz 

[root@90sec src]# cd keepalived-1.2.12

[root@90sec keepalived-1.2.12]# ./configure --prefix=/usr/local/keepalived --with-dir=/usr/src/kernels/*/

[root@90sec keepalived-1.2.12]# make && make install

[root@90sec keepalived-1.2.12]# mkdir /etc/keepalived

[root@90sec keepalived-1.2.12]# cp -f keepalived/etc/keepalived/keepalived.conf /etc/keepalived/

[root@90sec keepalived-1.2.12]# cp -f keepalived/etc/init.d/keepalived.init /etc/init.d/keepalived[root@90sec keepalived-1.2.12]# cp -f keepalived/etc/init.d/keepalived.sysconfig /etc/sysconfig/keepalived

[root@90sec keepalived-1.2.12]# cp -f /usr/local/keepalived/sbin/keepalived /sbin/


修改keepalived的配置文件

    ## nginx-master###

[root@90sec keepalived-1.2.12]# vim /etc/keepalived/keepalived.conf


! Configuration File for keepalived      #全局定义


global_defs {

   notification_email {

     [email protected]         #发生故障时给谁发送邮件

   }

   notification_email_from root@localhost   #故障用那个邮箱发送邮件

   smtp_server 127.0.0.1      #指定发送email的smtp服务器

   smtp_connect_timeout 30    #超时时间

   router_id LVS_DEVEL       #运行keepalived的机器的一个标识

}

vrrp_script chk_nginx {       #检测nginx服务是否在运行有很多方式,比如进程,用脚本检测等等 

   script "killall -0 nginx"  #用shell命令检查nginx服务是否存在 

   interval 1                 #时间间隔为1秒检测一次 

   weight -2                  #当nginx的服务不存在了,就把当前的权重-2 

   fall 2                     #测试失败的次数 

   rise 1                     #测试成功的次数 

vrrp_instance VI_1 {

    state MASTER              #为主服务器

    interface eth0            #监听的本地网卡接口

    virtual_router_id 51     #主辅virtual_router_id号必须相同 

    mcast_src_ip=192.168.83.132  #主nginx的IP地址

    priority 100                #优先级

    advert_int 1                ###同步间隔时长

    authentication {            #认证

        auth_type PASS            #认证方式

        auth_pass 1111            #密钥

    }

    virtual_ipaddress {

        192.168.83.131/24 dev eth1  #VIP

    }

}

##后面的就都用不到了删除就可以


####nginx-backup####

  ! Configuration File for keepalived

   

   global_defs {

      notification_email {

        [email protected]

      }

      notification_email_from root@localhost

      smtp_server 127.0.0.1

      smtp_connect_timeout 30

     router_id LVS_DEVEL

 }

  

  vrrp_instance VI_1 {

      state MASTER

      interface eth0

      virtual_router_id 51

     mcast_src_ip=192.168.83.133      #修改为133

      priority 90                    #修改为90

      advert_int 1

      authentication {

          auth_type PASS

          auth_pass 1111

     }

      virtual_ipaddress {

          192.168.83.131/24 dev eth1

     }

  }


启动keepalived服务(主辅两台)

[root@90sec keepalived-1.2.12]# /etc/init.d/keepalived start

Starting keepalived:                                       [  OK  ]

[root@90sec keepalived-1.2.12]# chkconfig --add keepalived

[root@90sec keepalived-1.2.12]# chkconfig keepalived on


查看vip是否主动切换

    nginx-maser上keepalived关闭之前

    wKiom1QdSybhXx8eAAHXOO5HmH4666.jpg


nginx-master上keepalived关闭之后

   wKioL1QdS3vD_4nrAAG-uXTQDP0070.jpg 

wKiom1QdS3mSdfNsAAH6l1SEURs188.jpg


四、修改nginx配置文件做反向代理

1、分别在web1,web2安装httpd服务

[root@70sec ~]# yum -y install httpd    

[root@70sec ~]# echo "<h1>Welcome to WEB1</h1>" > /var/www/html/index.html

[root@70sec ~]# service httpd restart

Stopping httpd:                                            [FAILED]

Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name, using 70sec.com for ServerName

                                                           [  OK  ]

[root@70sec ~]# curl http://192.168.83.134

    <h1>Welcome to WEB1</h1>


[root@10sec ~]# yum -y install httpd

[root@10sec ~]# echo "<h1>Welcome to WEB2</h1>" > /var/www/html/index.html

[root@10sec ~]# service httpd start

Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name, using 10sec.com for ServerName

                                                           [  OK  ]

[root@10sec ~]# curl httpd://192.168.83.135

    <h1>Welcome to WEB2</h1>


2、修改nginx的配置文件做反向代理(主辅配置文件相同)

user  nginx nginx;        ##运行nginx的用户和组

worker_processes  2;        ##启动进程数


#error_log  logs/error.log;

#error_log  logs/error.log  notice;

#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {

    use epoll;                            ##工作模型

    worker_connections  1024;             ##单进程最大连接数

}



http {                                ##http模块

    include       mime.types;        ##包含进来

    default_type  application/octet-stream;    ##默认类型

    

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '

    #                  '$status $body_bytes_sent "$http_referer" '

    #                  '"$http_user_agent" "$http_x_forwarded_for"';


    #access_log  logs/access.log  main;


    sendfile        on;

    #tcp_nopush     on;


    #keepalive_timeout  0;

    keepalive_timeout  65;                ##长连接时长


    #gzip  on;


upstream web {                       ##用upstream定义集群与RS     

       

        server 192.168.83.134:80  weight=1 max_fails=3 fail_timeout=10s;  ##RS地址,错误请求与超时时长

        server 192.168.83.135:80  weight=1 max_fails=3 fail_timeout=10s;


}

    server {

        listen       80;            ##监听端口

        server_name  192.168.83.131;    ##ServerName

        

        root html;

        index index.html index.htm;

        #charset koi8-r;


        #access_log  logs/host.access.log  main;

        location / {

                proxy_pass http://web;    ##反向代理

                proxy_redirect off;

                proxy_set_header X-Real-IP $remote_addr;

                proxy_set_header X-Forwarded-For Proxy_add_x_forwarded_for;

        }

        #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;

        }

        error_page   500 502 503 504  /50x.html;

        location = /50x.html {

            root   html;

        }

3、拷贝到nginx-backup上

    [root@90sec sbin]# scp /usr/local/nginx/conf/nginx.conf 192.168.83.133:/usr/local/nginx/conf/


测试代理

    wKioL1Qeez3jkjNZAACVJg8GPjc066.jpg

wKioL1QefHjQSTd9AAClg7ySd8E458.jpg

测试负载

现在关掉web1

 

[root@70sec ~]# service httpd stop

Stopping httpd:                                            [  OK  ]

   wKiom1QefGXxmuhYAAClg7ySd8E199.jpg

再开启web1,关闭web2

[root@70sec ~]# service httpd start

Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name, using 70sec.com for ServerName

                                                           [  OK  ]

[root@10sec ~]# service httpd stop

Stopping httpd:                                            [  OK  ]

wKioL1QefMmRlrFpAACVJg8GPjc709.jpg

upstream 支持的负载均衡算法

Nginx的负载均衡模块目前支持4种调度算法,下面进行分别介绍,其中后两项属于第三方调度算法。  

轮询(默认)。每个请求按时间顺序逐一分配到不同的后端服务器,如果后端某台服务器宕机,故障系统被自动剔除,使用户访问不受影响。Weight 指定轮询权值,Weight值越大,分配到的访问机率越高,主要用于后端每个服务器性能不均的情况下。

ip_hash。每个请求按访问IP的hash结果分配,这样来自同一个IP的访客固定访问一个后端服务器,有效解决了动态网页存在的session共享问题。

fair。这是比上面两个更加智能的负载均衡算法。此种算法可以依据页面大小和加载时间长短智能地进行负载均衡,也就是根据后端服务器的响应时间来分配请求,响应时间短的优先分配。Nginx本身是不支持fair的,如果需要使用这种调度算法,必须下载Nginx的upstream_fair模块。

url_hash。此方法按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,可以进一步提高后端缓存服务器的效率。Nginx本身是不支持url_hash的,如果需要使用这种调度算法,必须安装Nginx 的hash软件包。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章