keepalive 实现 nginx 高可用
实验背景: 两台 centos7 服务器,分别装有 nginx,nginx 设置反向代理 apache web。
nginx1 ip:10.2.7.204, nginx2: 10.2.7.205, vip: 10.2.7.210
nginx1,nginx2 下载安装 keepalived
yum install -y keepalived
nginx1,nginx2 增加检测 nginx 是否运行文件 check_nginx.sh
cat /etc/keepalived/check_nginx.sh
#!/bin/bash
counter=$(ps -C nginx --no-heading|wc -l)
if [ "${counter}" = "0" ]; then
systemctl start nginx
#/usr/local/bin/nginx
sleep 2
counter=$(ps -C nginx --no-heading|wc -l)
if [ "${counter}" = "0" ]; then
#/etc/init.d/keepalived stop
systemctl stop keepalived
fi
fi
nginx1 配置 keepalive
cat /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
notification_email {
zhouxiao@example.com
itsection@example.com
}
notification_email_from itsection@example.com
smtp_server mail.example.com
smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_script chk_nginx {
# script "killall -0 nginx"
script "/etc/keepalived/check_nginx.sh"
interval 2
weight -5
fall 3
rise 2
}
vrrp_instance VI_1 {
state MASTER
interface eth0
mcast_src_ip 10.2.7.204
virtual_router_id 51
priority 101
advert_int 2
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
10.2.7.210
}
track_script {
chk_nginx
}
}
nginx2 配置 keepalive。在 BACKUP 上,只需要改变 state MASTER -> state BACKUP,priority 101 -> priority 100,mcast_src_ip 10.2.7.204 -> mcast_src_ip 10.2.7.205 即可
cat /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
notification_email {
zhouxiao@example.com
itsection@example.com
}
notification_email_from itsection@example.com
smtp_server mail.example.com
smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_script chk_nginx {
# script "killall -0 nginx"
script "/etc/keepalived/check_nginx.sh"
interval 2
weight -5
fall 3
rise 2
}
vrrp_instance VI_1 {
state BACKUP
interface eth0
mcast_src_ip 10.2.7.205
virtual_router_id 51
priority 100
advert_int 2
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
10.2.7.210
}
track_script {
chk_nginx
}
}
nginx 配置 apache web 反向代理参考前面文章 centos7 使用 nginx 反向代理,web 端高可用
至此,访问 vip 10.2.7.210 即可访问后端的 web 页面,即使 nginx1 和 nginx2 中任何一个挂掉,也不影响访问 web 页面。当然 web1 和 web2 任何一个挂掉也不会受影响。实现了nginx 和 web 的高可用
http://seanlook.com/2015/05/18/nginx-keepalived-ha/
http://www.178linux.com/75869