1. 安装:
    yum -y install keepalived
  2. 配置:
    vim /etc/keepalived/keepalived.conf
    1. 主:
      ! Configuration File for keepalived
      global_defs {
      }
      vrrp_script chk_nginx {
      script "/etc/keepalived/check.sh"
      interval 1
      weight -15
      }
      vrrp_instance VI_1 {  #  实例,一个vip一个实例
      state MASTER
      interface eth0
      virtual_router_id 51
      priority 100
      advert_int 1
      authentication {
       auth_type PASS
       auth_pass 123456
      }
      virtual_ipaddress {
       192.168.8.201
      }
      track_script {
       chk_nginx
      }
      notify_master "/etc/keepalived/notify.sh master"
      notify_backup "/etc/keepalived/notify.sh backup"
      notify_fault "/etc/keepalived/notify.sh fault"
      }
    2. 从:
      ! Configuration File for keepalived
      global_defs {
      }
      vrrp_script chk_nginx {
      script "/etc/keepalived/check.sh"
      interval 1
      weight -15
      }
      vrrp_instance VI_1 {
      state BACKUP
      interface eth0
      virtual_router_id 51
      priority 99
      advert_int 1
      authentication {
       auth_type PASS
       auth_pass 123456
      }
      virtual_ipaddress {
       192.168.8.201
      }
      track_script {
       chk_nginx
      }
      notify_master "/etc/keepalived/notify.sh master"
      notify_backup "/etc/keepalived/notify.sh backup"
      notify_fault "/etc/keepalived/notify.sh fault"
      }
    3. 添加服务检查脚本(check.sh):
      vim /etc/keepalived/check.sh
      #!/bin/bash
      # 心跳检测:如果服务还在运行返回0,否则返回1
      if [ "`pgrep  nginx  |  wc  -l`" == "0" ] ; then
      exit 1
      else
      exit 0
      fi
    4. 通知脚本(notify.sh):
      vim /etc/keepalived/notify.sh
      #!/bin/bash
      # 通知脚本:具体操作
      if [ "$1" == "master" ] ; then
      echo "`date '+%F %T'`:切换到主机模式" >> /var/log/keepalived/keepalived.log
      elif [ "$1" == "backup" ] ; then
      /usr/bin/systemctl start nginx
      echo "`date '+%F %T'`:切换到备机模式" >> /var/log/keepalived/keepalived.log
      else
      /usr/bin/systemctl start nginx
      echo "`date '+%F %T'`:宕机" >> /var/log/keepalived/keepalived.log
      fi
    5. 给脚本添加可执行权限:
      chmod  +x  /etc/keepalived/check.sh
      chmod  +x  /etc/keepalived/notify.sh
    6. 创建日志目录:
      mkdir /var/log/keepalived
  3. 启动:
    systemctl start keepalived
文档更新时间: 2020-08-07 18:49   作者:lee