keepalived配置
VIP | IP | 主机名 | 默认主从 |
IP3 | ip1 | host1 | MASTER |
IP3 | ip2 | host2 | BACKUP |
1、master服务keepalived.conf配置
global_defs {
script_user root
enable_script_security
notification_email {
123@qq.com
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server ip1 #这里修改为本机IP
smtp_connect_timeout 30
router_id host1
}
#添加检测脚本
vrrp_script chk_http_port {
script "/etc/nginx/nginx_check.sh"
interval 2
weight 2
}
vrrp_instance VI_1 {
state MASTER #主机这里是MASTER 从机是BACKUP
interface ens3 #网卡
virtual_router_id 11 # 主、从机的virtual_router_id必须相同
priority 100 # 主备机取不同的优先级,主机优先级大
advert_int 1 #心跳检测间隔时间
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_http_port
}
virtual_ipaddress {
ip3 # VRRP 虚拟IP ;可换行输入多个进行绑定
}
}
2、backup服务keepalived.conf配置
global_defs {
script_user root
enable_script_security
notification_email {
123@qq.com
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server ip2 #这里修改为本机IP
smtp_connect_timeout 30
router_id host1 #主机名
}
#添加检测脚本
vrrp_script chk_http_port {
script "/etc/nginx/nginx_check.sh"
interval 2
weight 2
}
vrrp_instance VI_1 {
state BACKUP #主机这里是MASTER 从机是BACKUP
interface ens3 #网卡
virtual_router_id 11 # 主、从机的virtual_router_id必须相同
priority 90 # 主备机取不同的优先级,主机优先级大
advert_int 1 #心跳检测间隔时间
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_http_port
}
virtual_ipaddress {
ip3 # VRRP 虚拟IP ;可换行输入多个进行绑定
}
}
3、nginx_check.sh脚本
作用:检测nginx服务是否存在,如果不存在会主动关闭本机keepalived服务,这时本机虚拟IP消失,master服务器下线;backup服务器检测不到master服务的心跳会主动承担作为主服务作用直到重新启动master服务器的nginx和keepalived
#!/bin/sh
nginxpid=$(ps -C nginx --no-header|wc -l)
#判断Nginx是否存活
if [ $nginxpid -eq 0 ];then
systemctl stop keepalived
exit 1
fi
脚本写完需要给脚本文件执行权限: chmod +x /etc/keepalived/nginx_check.sh
常见的问题
1、防火墙
keepalived 基于vrrp(虚拟路由荣誉协议)实现,如果我们打开了防火墙就需要开放规则。否则可能会出现脑裂现象,表现为两台服务都挂载虚拟IP,可以通过ip a 命令查看服务器的IP地址。
firewall-cmd --direct --permanent --add-rule ipv4 filter INPUT 0 --in-interface ens160 --destination 224.0.0.18 --protocol vrrp -j ACCEPT
firewall-cmd --reload