keepalive的配置
#master配置
global_defs { router_id LVS_01 } #1.每5秒执行一次脚本, 脚本执行内容不能超过5秒,否则会被中断再次重新运行脚本 vrrp_script check_web { script "/server/scripts/check_web.sh" interval 5 } vrrp_instance VI_1 { nopreempt state BACKUP interface eth0 virtual_router_id 50 priority 150
nopreempt
advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 10.0.0.100 } #2.调用并运行该脚本 track_script { check_web } }
#backup配置,其他配置与master一样
vrrp_instance VI_1 {
state BACKUP
priority 100
nopreempt
}
脚本内容check_web
#!/bin/sh nginxpid=$(pidof nginx | wc -l) #1.判断Nginx是否存活,如果不存活则尝试启动Nginx if [ $nginxpid -eq 0 ];then systemctl start nginx sleep 2 #2.等待2秒后再次获取一次Nginx状态 nginxpid=$(pidof nginx | wc -l) #3.再次进行判断, 如Nginx还不存活则停止Keepalived,让地址进行漂移,并退出 脚本 if [ $nginxpid -eq 0 ];then systemctl stop keepalived fi fi #给脚本增加执行权限 [root@lb01 ~]# chmod +x /server/scripts/check_web.sh