Nginx+Keepalived双机热备方案通过Keepalived实现VIP(虚拟IP)的自动漂移,当主服务器故障时,备用服务器会自动接管VIP,确保服务不间断。
两台服务器(主备各一台)
确保两台服务器:
在两台服务器上执行:
# CentOS/RHEL
yum install keepalived -y
# Ubuntu/Debian
apt-get install keepalived -y
编辑/etc/keepalived/keepalived.conf
:
global_defs {
router_id nginx_master # 唯一标识,建议使用主机名
}
vrrp_script chk_nginx {
script "/usr/bin/killall -0 nginx" # 检测nginx进程是否存在
interval 2 # 每2秒检测一次
weight -20 # 检测失败时优先级降低20
}
vrrp_instance VI_1 {
state MASTER # 主服务器
interface eth0 # 网卡名称,根据实际情况修改
virtual_router_id 51 # 虚拟路由ID,主备必须相同
priority 100 # 优先级,主服务器高于备服务器
advert_int 1 # 主备同步检查间隔
authentication {
auth_type PASS
auth_pass 1111 # 密码,主备必须相同
}
virtual_ipaddress {
192.168.1.200 # 虚拟VIP
}
track_script {
chk_nginx # 关联nginx检测脚本
}
}
编辑/etc/keepalived/keepalived.conf
:
global_defs {
router_id nginx_backup
}
vrrp_script chk_nginx {
script "/usr/bin/killall -0 nginx"
interval 2
weight -20
}
vrrp_instance VI_1 {
state BACKUP # 备服务器
interface eth0
virtual_router_id 51
priority 90 # 优先级低于主服务器
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.1.200
}
track_script {
chk_nginx
}
}
在两台服务器上执行:
systemctl start keepalived
systemctl enable keepalived
ip addr show eth0
应该能看到VIP绑定在主服务器的eth0网卡上
systemctl stop nginx
观察VIP是否自动漂移到备服务器
恢复主服务器Nginx后,VIP应该会自动切回主服务器(因为主服务器优先级更高)
global_defs
中添加:notification_email {
admin@example.com
}
notification_email_from keepalived@example.com
smtp_server smtp.example.com
smtp_connect_timeout 30
多VIP支持: 在virtual_ipaddress
块中添加多个VIP
Nginx健康检查增强: 使用更复杂的检查脚本,例如:
#!/bin/bash
if [ "$(curl -s -o /dev/null -w '%{http_code}' http://localhost/health)" = "200" ]; then
exit 0
else
exit 1
fi
VIP不漂移:
virtual_router_id
在主备服务器上一致priority
设置是否正确脑裂问题:
vrrp_instance
中添加unicast_peer
配置)日志查看:
journalctl -u keepalived -f
通过以上配置,您就实现了Nginx的高可用双机热备方案,确保在单台服务器故障时服务能够自动切换,保障业务连续性。