1. 增加Nginx重启检测脚本

  1. vim /etc/keepalived/check_nginx_alive_or_not.sh
  1. #!/bin/bash
  2. A=`ps -C nginx --no-header |wc -l`
  3. # 判断nginx是否宕机,如果宕机了,尝试重启
  4. if [ $A -eq 0 ];then
  5. /usr/local/nginx/sbin/nginx
  6. # 等待一小会再次检查nginx,如果没有启动成功,则停止keepalived,使其启动备用机
  7. sleep 3
  8. if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
  9. killall keepalived
  10. fi
  11. fi
  • 增加运行权限
    chmod +x /etc/keepalived/check_nginx_alive_or_not.sh

    2. 配置keepalived监听nginx脚本

    1. vrrp_script check_nginx_alive {
    2. script "/etc/keepalived/check_nginx_alive_or_not.sh"
    3. interval 2 # 每隔两秒运行上一行脚本
    4. weight 10 # 如果脚本运行成功,则升级权重+10
    5. # weight -10 # 如果脚本运行失败,则升级权重-10
    6. }

    3. 在vrrp_instance中新增监控的脚本

    1. track_script {
    2. check_nginx_alive # 追踪 nginx 脚本
    3. }

    4. 重启Keepalived使得配置文件生效

    1. systemctl restart keepalived