一、基础环境

master: 192.168.203.128
slave: 192.168.203.129
VIP 192.168.203.130

二、安装keepalive

1、 创建依赖环境

yum -y install openssl-devel gcc gcc-c++
mkdir /etc/keepalived
wget https://www.keepalived.org/software/keepalived-2.0.18.tar.gz

2、安装keepalived

tar -zxvf keepalived-2.0.18.tar.gz
mv keepalived-2.0.18 /usr/local/keepalived
cd /usr/local/keepalived
./configure && make && make install

3、创建启动文件

cp  -a /usr/local/etc/keepalived   /etc/init.d/
cp  -a /usr/local/etc/sysconfig/keepalived    /etc/sysconfig/
cp  -a /usr/local/sbin/keepalived    /usr/sbin/

4、创建配置文件

1 master
vim /etc/keepalived/keepalived.conf

global_defs {
       router_id internal_control
}
vrrp_instance VI_1 {
       state MASTER
       interface ens33
       virtual_router_id 3
       priority 200
       advert_int 1 
       authentication {
               auth_type PASS
               auth_pass 123456
       }
       virtual_ipaddress {
               192.168.203.130/24

       }
}

2 slave
vim /etc/keepalived/keepalived.conf

global_defs {
       router_id internal_control
}
vrrp_instance VI_1 {
       state BACKUP
       interface ens33
       virtual_router_id 3
       priority 90
       advert_int 1 
       authentication {
               auth_type PASS
               auth_pass 123456
       }
       virtual_ipaddress {
               192.168.203.130/24

       }
}

5、启动keepalived(2台机器)

systemctl start keepalived
systemctl enable keepalived

查看maser上已经有vip地址了
centos7系统keepalvie高可用(抢占式)

三、测试

1 master关闭keepalived

systemctl stop keepalived 

2 salve查看vip地址
centos7系统keepalvie高可用(抢占式)

四、定时任务监控应用程序

每隔60秒进行一次检查应用程序和keepalived

定时任务:
* * * * *  /bin/bash /etc/keepalived/chk_internal.sh > /etc/keepalived/chk_log.log
脚本:
#!/bin/bash
APP_CODE="internal-control server"
KEEPALIVED_CODE="keepalived"
app_status=$(ps aux|grep "${APP_CODE}" | grep -v grep | wc -l)
if [ ${app_status} -eq 0 ]; then
    # 应用进程挂了
    sleep 20
    # 超过20秒应用程序还没起来,就关闭keepalived(时间可长可小,看情况而定)
    app_status2=$(ps aux|grep "${APP_CODE}" | grep -v grep | wc -l)
    if [ ${app_status} -eq 0 ]; then
         /usr/bin/systemctl stop keepalived
         /usr/bin/date
         echo "关闭keepalived"
    fi
else
   # 有应用进程的时候,检查keeplived是否关闭
   keepalive_status=$(ps aux|grep "${KEEPALIVED_CODE}" | grep -v grep | wc -l)
   if [ ${keepalive_status} -eq 0 ];then
       /usr/bin/systemctl start keepalived
       /usr/bin/date
       echo "开启keepalived"
   fi
fi
/usr/bin/date
echo "每隔1分钟执行检查成功"