1. 增加nginx 检查脚本
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
# 等待3秒检查nginx 如果没有启动成功 则停止keepalived 启动备用机
sleep 3s
if [ `ps -C nginx --no-header | wc -l` -eq 0 ];then
killall keepalived
fi
fi
增加执行权限:
# 增加运行权限
chmod +x /etc/keepalived/check_nginx_alive_or_not.sh
2. 配置keepalived监听nginx脚本
vrrp_script check_nginx_alive {
script "/etc/keepalived/check_nginx_alive_or_not.sh"
interval 2 #每隔2秒运行一次
weight 10 # 运行成功 权重加10
}
3. 在vrrp_ instance 中新增监控脚本
track_script {
check_nginx_alive # 添加nginx脚本
}
最后脚本预览:
global_defs {
router_id keep_101
}
vrrp_script check_nginx_alive {
script "/etc/keepalived/check_nginx_alive_or_not.sh"
interval 2 #每隔2秒运行一次
weight 10 # 运行成功 权重加10
}
vrrp_instance VI_1 {
state MASTER
interface ens33
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
check_nginx_alive # 添加nginx脚本
}
virtual_ipaddress {
192.168.235.150
}
}
4.重启Keepalived
service keepalived restart
完成上述步骤后,当Nginx宕机后可实现自动重启,实现24小时提供服务。
来源:oschina
链接:https://my.oschina.net/u/4326858/blog/4479407