- 增加Nginx重启检测脚本,放在/etc/keepalived/check_nginx.sh
#!/bin/bash
A=`ps -C nginx --no-header |wc -l`
# 判断nginx是否宕机,如果宕机了,尝试重启
if [ $A -eq 0 ];then
# 这里是nginx的路径
/usr/local/nginx/sbin/nginx
# 等待一小会再次检查nginx,如果没有启动成功,则停止keepalived,使其启动备用机
sleep 3
if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
killall keepalived
fi
fi
- 给脚本设置运行权限
chmod +x /etc/keepalived/check_nginx.sh
- 在Keepalived核心配置文件中配置脚本监听
vrrp_script check_nginx {
script "/etc/keepalived/check_nginx.sh"
# 每隔两秒运行上一行脚本
interval 2
# 如果脚本运行成功,则升级权重+10
weight 10
}
- 在 vrrp_instance 中新增监控的脚本
track_script {
# 追踪 nginx 脚本
check_nginx
}
- 重启使配置生效
systemctl restart keepalived