1. 增加Nginx重启检测脚本
vim /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
增加运行权限
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 # 每隔两秒运行上一行脚本
weight 10 # 如果脚本运行失败,则升级权重+10
}
3. 在 vrrp_instance 中新增监控的脚本
track_script {
check_nginx_alive # 追踪 nginx 脚本
}
4. 重启Keepalived使得配置文件生效
systemctl restart keepalived
下面是 MASTER Keepalived配置
! Configuration File for keepalived
global_defs {
# 路由id: 当前安装keepalived节点主机的标识符,全局唯一
router_id LVS_DEVEL_128
}
vrrp_script check_nginx_alive {
script "/etc/keepalived/check_nginx_alive_or_not.sh"
interval 2 # 每隔两秒运行上一行脚本
weight 10 # 如果脚本运行失败,则升级权重+10
}
# 计算机节点
vrrp_instance VI_1 {
# 表示的状态,当前的128位nginx的主机点,MASTER/BACKUP
state MASTER
# 当前实例绑定的网卡
interface ens33
# 保证主备节点一致
virtual_router_id 51
# 优先级/权重,谁的优先级高,在MASTER挂掉以后,就成为MASTER
priority 100
# 主备之间同步检查的时间间隔,默认1s
advert_int 1
# 认证密码,防止非法节点的进入
authentication {
auth_type PASS
auth_pass 1111
}
# 虚拟ip
virtual_ipaddress {
192.168.174.121
}
track_script {
check_nginx_alive # 追踪 nginx 脚本
}
}