Keeplived配置Nginx双机高可用【转】
精选
转载
原文:http://bbs.51cto.com/thread-1021620-1.html
一、简介不管是Keepalived还是Heartbeat做高可用,其高可用,都是站在服务器脚本去说的高可用,而不是服务的角度。也就是说,如果服务器DOWN机或者网络出现故障,高可用是可以实现自动切换的。如果运行的服务,比如Nginx挂掉这些高可用软件是意识不到的,需要自己写脚本去实现服务的切换。二、安装配置Keepalived复制内容到剪贴板
代码:
# ./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/
编辑MASTER的主配置文件(MASTER: 1.1.1.1)复制内容到剪贴板
代码:
# vim /etc/keepalived/keepalived.conf
! 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
}
}
编辑BACKUP的主配置文件(BACKUP:1.1.1.2)复制内容到剪贴板
代码:
# vim /etc/keepalived/keepalived.conf
! 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
编写监控Nginx的脚本复制内容到剪贴板
代码:
# 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
改进脚本,加上报警功能。复制内容到剪贴板
代码:
# 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邮箱,在139邮箱里面设置有邮件的时候,通知到手机,并且以长短信的方式。需要开户本机的sendmail服务。