本文旨在说明如何用 keepalived 实现某个服务的 主从热备 模式的高可用,主要提供了相关配置文件,配置文件中以 Nginx 服务为例。
一 keepalived 实现高可用的基本原理
keepalived 借助目标服务状态检查脚本判断是否进行代理漂移。
目标服务状态检查脚本中的逻辑是:如果目标服务没有运行,则尝试启动目标服务,等待一定时间后,如果目标服务仍未启动,则关闭对应的 keepalived ,进行 keepalived 代理漂移。
二 keepalived 的相关配置文件
(1)master上的配置:
! Configuration File for keepalived
global_defs {
notification_email {
1807479153@qq.com
}
notification_email_from pve@example.com
smtp_server mail.example.com
smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_script chk_nginx {
script "/etc/keepalived/nginx_check.sh"
interval 2
weight -5
fall 3
rise 2
}
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 2
priority 101
advert_int 2
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.207.210
}
track_script {
chk_nginx
}
}
! Configuration File for keepalived
global_defs {
notification_email {
1807479153@qq.com
}
notification_email_from pve@example.com
smtp_server mail.example.com
smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_script chk_nginx {
script "/etc/keepalived/nginx_check.sh"
interval 2
weight -5
fall 3
rise 2
}
vrrp_instance VI_1 {
state BACKUP
interface eth0
virtual_router_id 2
priority 100
advert_int 2
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.207.210
}
track_script {
chk_nginx
}
}
processCount=`ps -ef | grep nginx | grep -v grep | wc -l`
if [ $processCount -eq 0 ];then
# try to start Nginx
nginx
# suspended time 2 seconds
sleep 2
if [ `ps -ef | grep nginx | grep -v grep | wc -l` -eq 0 ];then
# kill keepalived and floating the VIP
ps -ef|grep keepalived|grep -v grep|awk '{print $2}'|xargs kill -9
fi
fi