背景
公司有几段公网是用云主机做网关的,且与IDC互联的是/30的一个IP。为了业务可靠,避免网关单点问题,需要做主备两个网关。主的宕机能自动切去备用网关。
施作方案
CentOS+Keepalived+float vip
开始部署
实验环境拓扑图如下所示:
一、配置CentOS云主机
主要是开设两台Centos6.9云主机,挂好两个网卡,一个做WAN卡,一个做LAN卡。配置好IP地址,启用路由转发,iptables配置允许转发。
此处不是重点,具体步骤不阐述。
二、安装Keepalived并配置
Centos6.9下可以直接yum安装,如果提示没有找到包,可以先安装epel源
yum install epel-release -y
yum install keepalived -y
接下来配置keepalived
Master配置如下:
vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
notification_email {
XXX@nxera.net
XXXXX@qq.com
}
notification_email_from root@localhost
smtp_server localhost
smtp_connect_timeout 30
router_id GW01
}
vrrp_script chk_maintainace {
script "/etc/keepalived/health_check.sh"
interval 3
weight -2
}
vrrp_instance VI_1 {
state MASTER
interface eth1
virtual_router_id 51
priority 101
advert_int 1
authentication {
auth_type PASS
auth_pass 123456
}
track_script {
chk_maintainace
}
virtual_ipaddress {
192.168.10.254/24 dev eth1
192.168.0.253/24 dev eth0
}
notify_master "/etc/keepalived/autosw.sh master"
notify_backup "/etc/keepalived/autosw.sh backup"
notify_fault "/etc/keepalived/autosw.sh fault"
}
Backup配置:
! Configuration File for keepalived
global_defs {
notification_email {
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
notification_email_from root@localhost
smtp_server localhost
smtp_connect_timeout 30
router_id GW02
}
vrrp_script chk_maintainace {
script "/etc/keepalived/health_check.sh"
interval 3
weight -2
}
vrrp_instance VI_1 {
state BACKUP
interface eth1
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 123456
}
track_script {
chk_maintainace
}
virtual_ipaddress {
192.168.10.254/24 dev eth1
192.168.0.253/24 dev eth0
}
notify_master "/etc/keepalived/autosw.sh master"
notify_backup "/etc/keepalived/autosw.sh backup"
notify_fault "/etc/keepalived/autosw.sh fault"
}
解释下上述配置的意思:
这边是邮件通告的相关配置,此方案另有脚本方式邮件告警。
最下面是标识ID,根据不同角色区别开就好。
此处配置了一个网关机器健康检查的脚本,每3秒检查一次。出问题了的话,优先级降级2.
配置文件中会使用到的脚本内容
health_check.sh,脚本返回值为1时,表明不健康。
###health_check.sh
#!/bin/bash
#
if [ "`ip addr show | grep 192.168.0.253`" == "" ] || [ "`ip addr show | grep 192.168.10.254`" == "" ];then
# echo "$? Is Null"
exit 1
else
# echo "$? Not Null"
exit 0
fi
autosw.sh,此脚本参考博文:https://blog.51cto.com/13520924/2094236
此脚本能生效的前提是,网关机器能成功发送邮件。本方案按照的是sendmail,然后在/etc/mail.rc最后面加上smtp信息
###autosw.sh
#!/bin/bash
#
contact='354519347@qq.com'
notify() {
mailsubject="$(hostname) to be $1, vip floating"
mailbody="$(date +'%F %T'): vrrp transition, $(hostname) changed to be $1"
echo "$mailbody" | mail -s "$mailsubject" $contact
}
case $1 in
master)
notify master
;;
backup)
notify backup
;;
fault)
notify fault
;;
*)
echo "Usage: $(basename $0) {master|backup|fault}"
exit 1
;;
esac
三、启动keepalived并设置开机自启
分别在主备两台网关机器上面输入下面指令
service keepalived start
chkconfig keepalived on
四、检查浮动IP,以及自动切换功能
Master:
Backup:
给Master使点坏(关机或者ifdown一个网卡),观察浮动IP和网络稳定状况
Master网关恢复后,浮动IP也会自动切回。