场景:操作系统环境为centos7.9 这里举例了定时检测一个http接口,若超过4次返回不为200则切换master到backup 同时若当前节点被切换为备份节点需要执行一个自己的脚本
两台虚拟机 准备一个vip
1.安装keepalived yum install keepalived
2.配置文件路径/etc/keepalived/keepalived.conf
3.master 节点配置
! Configuration File for keepalived
global_defs {
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id LVS_DEVEL
vrrp_skip_check_adv_addr
#vrrp_strict
vrrp_garp_interval 0
vrrp_gna_interval 0
script_user root
enable_script_security
}
vrrp_script chk_url {
script "/etc/keepalived/check.sh"
interval 5
weight 2
rise 4
fall 4
}
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 99
priority 99
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.200.16
}
track_script {
chk_url
}
notify_backup "/etc/keepalived/keepalive.sh"
}
4.backup配置
! Configuration File for keepalived
global_defs {
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id LVS_DEVEL
vrrp_skip_check_adv_addr
#vrrp_strict
vrrp_garp_interval 0
vrrp_gna_interval 0
script_user root
enable_script_security
}
vrrp_script chk_url {
script "/etc/keepalived/check.sh"
interval 1
weight 2
}
vrrp_instance VI_1 {
state BACKUP
interface eth0
virtual_router_id 99
priority 98
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.200.16
}
track_script {
chk_url
}
notify_backup "/etc/keepalived/keepalive.sh"
}
这里说明下 chk_url函数就是配置你需要检测的脚本
interval 间隔执行周期秒
weight 权重值
rise 判断一个服务正常工作之前需要连续成功的检测次数
fall 失败次数 切换备节点
track_script 这个设置后才会开始触发执行我们的脚本
notify_master 当前节点切换成主节点时触发
notify_backup 当前节点切换成备节点时触发
notify 当前节点切换成主/备节点和发生切换异常时触发
5.脚本示例
check.sh
#!/bin/bash
API_URL="http://xxx"
response=$(curl -s -o /dev/null -w "${http_code}" "$API_URL")
if [ $response != "200" ]; then
exit 1
else
exit 0
fi
keepalive.sh
#!/bin/bash
#根据自己业务需求执行对应的shell命令
systemctl restart xxx
注意事项:
- 检测脚本需要放在/etc/keepalived/
- 脚本的权限为 chmod 744 或者755(设置777不行)
- 其他配置未使用可以删除掉,按照我的配置
- vrrp_strict 这个需要注释掉,不然vip无法访问
- script_user root enable_script_security 这两个需要添加上,不然启动会报错
- virtual_router_id 主备一定需要一致且在你的环境中需要唯一
- priority 设置的数字主>备
- authentication 主备需要一致
- interface 设置网卡 需要ip addr设置准确
- 脚本设置需要返回指定的值,keepalived是根据返回来判断是否正常
- 日志文件是写在/var/log/message 可以过滤下keepalived关键字
- 若只是由于检测监听的脚本的服务异常,直接查看master节点日志就可以看见主备切换
- 当keepalived服务停止后 可以在backup查看切换日志