無論 Keepalived 還是 Heartbeat,其所謂高可用是站在「伺服器」層級:機器宕機或網路中斷時能自動切換 VIP。但如果機器還活著、只是 Nginx 進程掛了,這類軟體並不察覺,必須自己寫腳本補上服務層的切換。
./configure make make install cp /usr/local/etc/rc.d/init.d/keepalived /etc/rc.d/init.d/ cp /usr/local/etc/sysconfig/keepalived /etc/sysconfig/ cp /usr/local/sbin/keepalived /usr/bin/ chkconfig --add keepalived mkdir /etc/keepalived/ cp /usr/local/etc/keepalived/keepalived.conf /etc/keepalived/
! Configuration File for keepalived
global_defs {
router_id LVS_DEVEL
}
vrrp_script chk_nginx {
script "/opt/monnginx.sh"
interval 2
weight 2
}
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass mdnginx
}
virtual_ipaddress {
1.1.1.100
}
track_script {
chk_nginx
}
}
與主機唯一的差異是 state BACKUP,其餘保持一致:
! Configuration File for keepalived
global_defs {
router_id LVS_DEVEL
}
vrrp_script chk_nginx {
script "/opt/monnginx.sh"
interval 2
weight 2
}
vrrp_instance VI_1 {
state BACKUP
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass mdnginx
}
virtual_ipaddress {
1.1.1.100
}
track_script {
chk_nginx
}
}
主備兩台都要執行:
service nginx start service keepalived start
vim /opt/monnginx.sh
#!/bin/bash
# author: honway.liu
# date: 2013-03-15
if [ $(ps -C nginx --no-header | wc -l) -eq 0 ]; then
service nginx start
fi
sleep 3
if [ $(ps -C nginx --no-header | wc -l) -eq 0 ]; then
service keepalived stop
fi
邏輯是:發現 Nginx 不在就嘗試拉起,等 3 秒再確認;若仍失敗,就停掉本機 Keepalived,讓 VIP 漂移到對端。
vim /opt/monnginx.sh
#!/bin/bash
# author: honway.liu
# date: 2013-03-15
IPADDR=$(ip addr show eth0 | awk '{print $2}' | sed -n 3p)
contact=(137XXXXXXXX@139.com)
num=${#contact[@]}
function email() {
for ((i=0;i<num;i++)); do
echo "$IPADDR service problem" | mail -s "WARNING" ${contact[i]} -- -f gm100861@gmail.com
done
}
if [ $(ps -C nginx --no-header | wc -l) -eq 0 ]; then
service nginx start
fi
email
sleep 3
if [ $(ps -C nginx --no-header | wc -l) -eq 0 ]; then
service keepalived stop
email
fi
這裡用 139 郵箱做告警通道,該郵箱可設定「收到郵件時通知手機」,並以長短信形式呈現。使用前需啟動本機 sendmail 服務。