Ubuntu 16.04 Nginx+keepalived 负载均衡

590 阅读2分钟

机器IP

hostnameIP备注
Master192.168.1.10Nginx主机 任务分发
Backup192.168.1.11Nginx 备机
node1192.168.1.12任务处理1
node2192.168.1.13任务处理2

操作系统以及软件版本

  • OS Ubuntu 16.04 LTS
  • Nginx 1.10.3
  • Keepalived v1.2.24
  • VIP 39.10.110.110

安装过程

sudo apt-get install -y libssl-dev libssl libpopt-dev
sudo apt-get install nginx
sudo apt-get install keepalived

Nginx 配置简单的负载均衡

Nginx主机和备机Nginx配置

此处省略
upstream loadbalance {
     server 192.168.1.12 weight=1;
     server 192.168.1.13 weight=2;
}
server {
        listen 8008 default_server;
        listen [::]:8008 default_server;
        location / {
                proxy_pass http://loadbalance;
        }
}

192.168.1.12/13机器Nginx修改 /var/www/html/default.html 文件中的内容,以便于区分访问的页面

<body>
<h1>Welcome to nginxIP*!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<body>

配置keepalived

sudo vim /etc/keepalived/keepalived.conf

主Nginx配置

global_defs {
    notification_email {
      xxxxx@qq.com
    }
    notification_email_from xxxx@163.com
    smtp_server smtp.163.com
    smtp_connection_timeout 30
    router_id nginx_master
}
vrrp_script chk_http_port {
    script "/usr/local/src/check_nginx_pid.sh"
    interval 10 #轮询
    weight 2
}

vrrp_instance VI_1 {
    state MASTER
    interface enp3s0f0
    virtual_router_id 66
    priority 100
    advert_int 1
    authentication {
       auth_type PASS
       auth_pass 1111
    }
    track_script {
       chk_http_port
    }
    virtual_ipaddress {
       39.10.110.110
    }
}

备Nginx配置

global_defs {
    notification_email {
      xxx@qq.com
    }
    notification_email_from xx@163.com
    smtp_server smtp.163.com
    smtp_connection_timeout 30
    router_id nginx_backup
}
vrrp_script chk_http_port {
    script "/usr/local/src/check_nginx_pid.sh"
    interval 2
    weight 2
}

vrrp_instance VI_1 {
    state BACKUP
    interface enp2s0f0
    virtual_router_id 66
    priority 99
    advert_int 1
    authentication {
       auth_type PASS
       auth_pass 1111
    }
    track_script {
       chk_http_port
    }
    virtual_ipaddress {
       39.10.110.110
    }
}

补充 /usr/local/src/check_nginx_pid.sh此文件需要有执行权限chmod a+rwx

#/bin/bash
A=`ps -C nginx --no-header | wc -l`
if [ $A -eq 0 ];then
    service  nginx restart
    if [ `ps -C nginx --no-header | wc -l` -eq 0 ];then
        killall keepalived
    fi
fi

测试过程

关闭主机的Nginx服务 出现网站短时间内无法访问的情况,过几秒后可以访问。原因是keepalived每隔10s去执行一次check_nginx_pid.shchk_http_port,然后重启nginx才能访问 关闭主机的Nginx服务和Keepalived服务 出现网站无法访问的情况,过会儿又可以访问了。这个因为Nginx备机接替主机工作。测试过程时间有点长,原因在检查中,如果您有相关经验,请留言,谢谢!

 Keepalived_vrrp[9033]: VRRP_Instance(VI_1) Transition to MASTER STATE
 VRRP_Instance(VI_1) Effective priority = 102
 VRRP_Instance(VI_1) Entering MASTER STATE