什么是KeepAlived
参考来源:https://www.bilibili.com/video/BV1JS4y1P7UY/?spm_id_from=333.880.my_history.page.click&vd_source=7985f01e8feeaad6888cfabd30aaa784
检测脚本
cat >/etc/keepalived/chk_nginx.sh<< EOF
#!/bin/bash
count=$(pgrep nginx|wc -l)
if ["${counter}" = "0"];then
systemctl restart nginx
sleep 2
count=$(pgrep nginx|wc -l)
if ["${counter}" = "0"];then
systemctl stop keepalived
fi
fi
EOF
chmod 755 /etc/keepalived/chk_nginx.sh
主节点配置
Nginx配置
<html>
<head>
<meta charset="UTF-8">
<title>主</title>
</head>
<h1>
我是主节点
</h1>
</html>
Keepalived配置
cat > /etc/keepalived/keepalived.conf << EOF
! Configuration File for keepalived
global_defs {
router_id LVS_DEVEL
}
vrrp_script chk_nginx {
script "/etc/keepalived/chk_nginx.sh"
interval 2
weight ‐5
}
vrrp_instance VI_1 {
state MASTER
interface ens33
virtual_router_id 51
priority 100
advert_int 2
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.113.192
}
track_script {
chk_nginx
}
}
EOF
systemctl restart keepalived.service
备份节点配置
Nginx配置
<html>
<head>
<meta charset="UTF-8">
<title>备份</title>
</head>
<h1>
我是备份节点
</h1>
</html>
Keepalived配置
cat > /etc/keepalived/keepalived.conf << EOF
! Configuration File for keepalived
global_defs {
router_id LVS_DEVEL
}
vrrp_script chk_nginx {
script "/etc/keepalived/chk_nginx.sh"
interval 2
weight ‐5
}
vrrp_instance VI_1 {
state BACKUP
interface ens33
virtual_router_id 51
priority 99
advert_int 2
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.113.192
}
track_script {
chk_nginx
}
}
EOF
systemctl restart keepalived.service
通过VIP访问nginx提供的页面
192.168.113.192
模拟故障
在Master上停止KeepAlived
systemctl stop keepalived.service
可以看到已经切换到备用节点,而用户通过vip访问所以无感知
查看日志
tail -f -n 50 /var/log/messages
Keepalived配置说明
! Configuration File for keepalived
# 全局配置,路由ID,固定不变
global_defs {
router_id LVS_DEVEL
}
# 定义Nginx状态脚本
vrrp_script chk_nginx {
script "/etc/keepalived/chk_nginx.sh"
# 间隔时间,单位为秒,默认1秒
interval 2
# 权重,当脚本成功或失败对当前节点的优先级是增加还是减少
weight ‐5
}
#VRRP实例
vrrp_instance VI_1 {
# 主节点
state MASTER
# 绑定的网卡,使用ifconfig命令查看获取
interface ens33
# 虚拟路由id,保证相同
virtual_router_id 51
# 优先级,抢占模式下优先级高的称为主
priority 101
# 指定发送VRRP通告的间隔。单位是秒。
advert_int 2
# 安全认证用的密码,自定义即可
authentication {
auth_type PASS
auth_pass 1111
}
# 对外暴露的VIP地址
virtual_ipaddress {
192.168.113.192
}
# 指定Nginx执行状态脚本
track_script {
chk_nginx
}
}