1 脚本文件
[root@localhost ~]# vi /etc/keepalived/check_nginx_alive_or_not.sh
#!/bin/bash
A=`ps -C nginx --no-header |wc -l`
# 判断nginx是否宕机,如果宕机了,尝试重启
if [ $A -eq 0 ];then
/usr/local/nginx/sbin/nginx
# 等待一小会再次检查nginx,如果没有启动成功,则停止keepalived,使其启动备用机
sleep 3
if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
killall keepalived
fi
fi
2 设置权限
[root@localhost ~]# chmod +x /etc/keepalived/check_nginx_alive_or_not.sh
3 配置脚本文件
3.1 配置keepalived监听nginx脚本
vrrp_script check_nginx_alive {
script "/etc/keepalived/check_nginx_alive_or_not.sh"
interval 2 # 每隔两秒运行上一行脚本
# weight 10 # 如果脚本运行成功,则升级权重+10
weight -10 # 如果脚本运行失败,则降低权重-10
}
3.2 在 vrrp_instance 中新增监控的脚本
track_script {
check_nginx_alive # 追踪 nginx 脚本
}
3.3 重启 Keepalived 服务
[root@localhost ~]# systemctl restart keepalived
4 测试功能
主节点停止nginx
服务,会自动重启依然可以正常访问主节点
[root@localhost keepalived]# /usr/local/nginx/sbin/nginx -s quit
主节点继续停止 keepalived
服务
[root@localhost keepalived]# systemctl stop keepalived
主节点重新启动 keepalived
服务,nginx
自动启动成功,恢复访问主节点
[root@localhost keepalived]# systemctl start keepalived
5 相关信息
- 博文不易,辛苦各位猿友点个关注和赞,感谢