Keepalived高可用

249 阅读1分钟

Keepalived 使用VRRP协议(虚拟路由冗余协议)

应用场景: 解决单点故障问题,实现高可用,一般与脚本配合使用。

方便测试

systemctl stop firewalld && systemctl disable firewalld && setenforce 0

加入阿里epel源

wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo

安装

yum -y install keepalived

虚拟IP 192.168.0.216

配置 MASTER

vim /etc/keepalived/keepalived.conf

! Configuration File for keepalived

global_defs {
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 192.168.200.1
   smtp_connect_timeout 30
   router_id LVS_DEVEL_109
}

vrrp_instance VI_1 {
    state MASTER
    interface ens33
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.0.216
    }
}

配置 BACKUP

vim /etc/keepalived/keepalived.conf

! Configuration File for keepalived

global_defs {
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 192.168.200.1
   smtp_connect_timeout 30
   router_id LVS_DEVEL_108
}

vrrp_instance VI_1 {
    state BACKUP
    interface ens33
    virtual_router_id 51
    priority 90
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.0.216
    }
}

启动 & 开机自启

systemctl start keepalived && systemctl enable keepalived

脚本实现当nginx进程不存在时自动切换至 keepalived 备用节点

方案一

写一个脚本,每2秒检测一下nginx进程是否存在,如果不存在则杀掉keepalived进程,则备用节点会抢占VIP。

vim /opt/chk_ngx.sh

#!/bin/bash
while true
do
    # 统计nginx进程数
    NGXP_NUM=`ps -C nginx --no-header | wc -l`

    # 如果nginx进程不存在则杀掉keepalived进程,备用keepalived会自动抢占VIP
    if [ $NGXP_NUM -eq 0 ];then
        systemctl stop keepalived
        exit
    fi
    sleep 2
done
chmod +x /opt/chk_ngx.sh
nohup /opt/chk_ngx.sh &

方案二 使用keepalived 的vrrp_script去调用脚本 vim /etc/keepalived/keepalived.conf

! Configuration File for keepalived

global_defs {
   ...
}

########## 这里配置调用哪个脚本 #############
vrrp_script check_nginx {
    script "/opt/chk_ngx.sh"
    interval 2
    weight -20
}

vrrp_instance VI_1 {
    ...
########## 这里配置调用哪个vrrp_script #############
    track_script
    {
        check_nginx
    }

}

cat /opt/chk_ngx.sh

#!/bin/bash

# 统计nginx进程数
NGXP_COUNT=`ps -C nginx --no-header | wc -l`

# 如果nginx进程不存在则杀掉keepalived进程,备用keepalived会自动抢占VIP
if [ $NGXP_COUNT -eq 0 ];then
    systemctl stop keepalived
fi

加权限

chmod +x /opt/chk_ngx.sh