Ubuntu安装Keepalived
1. 网络放通
vim /etc/iptables/rules.v4# 放行 VRRP 协议 112(多播/单播都兼容)
-A INPUT -p 112 -j ACCEPT
-A OUTPUT -p 112 -j ACCEPTiptables-restore < /etc/iptables/rules.v4下面流程走完可以抓包看keepalived通信:
tcpdump -i any host 【目标IP】 and ip proto 1122.ubuntu安装keepalived
sudo apt-get install keepalived
3.设置随系统自动启动
sudo vim /etc/rc.local#!/bin/sh -e
# 上面一行不要删除
# 服务类要以 & 结尾一行,表示不要等待运行结束
service keepalived start &
# 设置cpc-admin自动启动
# Change to the correct directory
cd /home/cpcnet/mnt/cpc-admin
# Execute the start.sh script with sudo
sudo ./start.sh
#文末必须以exit 0结束
exit 0设置rc.local的执行权限
sudo chmod +x /etc/rc.local4.配置keepalived.conf
sudo vim /etc/keepalived/keepalived.confxx.xx.xx.12为Master IP,xx.xx.xx.17为虚拟IP,配置内容如下:
global_defs {
router_id xx.xx.xx.12
}
vrrp_script chk_nginx {
script "/etc/keepalived/nginx_chk.sh"
interval 2
}
vrrp_instance VI_1{
state MASTER
interface ens192
virtual_router_id 100
priority 101
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
xx.xx.xx.17
}
track_script {
chk_nginx
}
}注意:配置文件中的interface需要通过ifconfig命令查询得出xx.xx.xx.12对应的物理网卡名称

xx.xx.xx.16为backup,配置内容如下:
global_defs {
router_id xx.xx.xx.16
}
vrrp_script chk_nginx {
script "/etc/keepalived/nginx_chk.sh"
interval 2
}
vrrp_instance VI_1{
state BACKUP
interface ens192
virtual_router_id 100
priority 101
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
xx.xx.xx.17
}
track_script {
chk_nginx
}
}注意:配置文件中的interface需要通过ifconfig命令查询得出xx.xx.xx.16对应的物理网卡名称

5.配置nginx_chk.sh,路径为/etc/keepalived/nginx_chk.sh
#!/bin/bash
#上面这句注释不可删除
#检查是否有nginx相关的进程
A=`ps -C nginx --no-header |wc -l`
#如果没有
if [ $A -eq 0 ];then
# 重启nginx,延迟2秒
service nginx restart
sleep 2
# 重新检查是否有nginx相关的进程
if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
# 仍然没有nginx相关的进程,杀死当前keepalived,切换到备用机
killall keepalived
fi
fi
6.为脚本文件添加执行权限
sudo chmod +x /etc/keepalived/nginx_chk.sh
7.测试脚本,如果有错误会输出错误信息,没有错误什么也不输出
cd /etc/keepalived
./nginx_chk.sh
8.重启keepalived
sudo service keepalived restart
9.检查keepalived重启是否成功
systemctl status keepalived.service

10.检查虚拟IP是否设置成功,以及能否切换
xx.xx.xx.12的虚拟IP已经设置进来了
ip a

xx.xx.xx.16(BACKUP)上没有虚拟IP
停掉Master的keepalived再检查(在xx.xx.xx.12执行以下命令)
sudo service keepalived stopip a
Master的虚拟IP没有了

backup上有了虚拟IP
ip a

11. 检查页面能否访问
先将上面停掉的master上的keepalived启动起来
sudo service keepalived start临时启动一个服务
python3 -m http.server --bind 0.0.0.0 443通过虚拟IP xx.xx.xx.17 访问
telnet xx.xx.xx.17 443赞(1)
赏