准备两台虚拟机,一台主,一台从,方便漂移vip
1.两台机器分别安装nginx
安装依赖环境
yum -y install gcc gcc-c++ pcre-devel zlib-devel
解压安装包配置安装一起执行
2.两台机器分别装上keepalived
yum -y install keepalived
3.配置keepalived文件
vim /etc/keepalived/keepalived.conf
#配置vrrp_script,主要用于健康检查,以及检查失败后执行的动作。
vrrp_script chk_nginx {
#健康检查脚本,当脚本返回值不为0时认为失败
script "/etc/keepalived/ck_ng.sh"
#检查频率,以下配置每2秒检查1次
interval 2
#当检查失败后,将vrrp_instance的priority减小5
weight -5
}
一定要注意网卡名称本台机子网卡名称是什么就写什么以免不能出现虚拟ip
这一块是自己定义的虚拟ip
配置检测ip
配置引用脚本模块
#本vrrp_instance所引用的脚本配置,名称就是vrrp_script 定义的容器名
track_script {
chk_nginx
}
4.在/ect/keepalived目录下写入脚本测试文件
vim /ect/keepalived/ck_ng.sh
#!/bin/bash
a=ss -ptlnu | grep 80 | wc -l
if [ $a = 0 ]
then
/usr/local/nginx/sbin/nginx
sleep 2
b=ss -ptlnu | grep 80 | wc -l
if [ $b = 0 ];then
pikll keeplived
fi
else
echo nginx is ok
fi
授予脚本执行权限
chmod +x ck_ng.sh
5.推送配置文件到从的机器上
scp /etc/keepalived/keepalived.conf root@10.0.0.46:/etc/keepalived/keepalived.conf
6.BACKUP服务器的配置需要几处修改
state MASTER改为 state BACKUP
mcast_src_ip 10.0.0.45改为backup服务器实际的IP mcast_src_ip 10.0.0.46
priority 100改为priority 99
7.开启keepalived进行测试
systemctl start keepalived
ip a 进行查看ip
杀死keepalived需要用pkill keepalived,systemctl stop keepalived 没有效果