环境:
master:Ubuntu 12.04(192.168.31.186)
backup: Ubuntu 12.04(192.168.31.110)
VIP: 192.168.31.100
keepalived的原理可以这样简单理解:
keepalived安装在两台物理服务器上,并相互监控对方是否在正常运行。
当master正常的时候:master上的keepalived会绑定vip(192.168.8.100)
tail -f /var/log/syslog
Feb 18 05:41:41 keepalived1 Keepalived_vrrp[2561]: VRRP_Instance(VI_1) Sending gratuitous ARPs on eth0 for 192.168.31.100
Feb 18 05:41:41 keepalived1 Keepalived_healthcheckers[2560]: Netlink reflector reports IP 192.168.31.100 added
Feb 18 05:41:46 keepalived1 Keepalived_vrrp[2561]: VRRP_Instance(VI_1) Sending gratuitous ARPs on eth0 for 192.168.31.100
当master发生故障的时候,backup上的keepalived会检测到,并且绑定vip(192.168.8.100)
即虚拟IP漂移至backup
当master恢复vip又重新绑定
安装
apt-get install keepalived
keepalived配置文件
vim /etc/keepalived/keepalived.conf
global_defs {
router_id L1
}
vrrp_instance VI_1 {
state MASTER //设置服务器模式,需要大写,备用机可以写 state BACKUP
interface eth0
virtual_router_id 51 //VRRP组名,两个节点的设置必须一样,以指明各个节点属于同一VRRP组
priority 100 //主节点的优先级(1-254之间),备用节点必须比主节点优先级低
advert_int 1
authentication { //设置验证信息,两个节点必须一致
auth_type PASS
auth_pass 123456
}
virtual_ipaddress { //指定虚拟IP, 两个节点设置必须一样
192.168.31.100
}
mastr和backup的区别是 state和priority
启动
service keepalived start
测试
在两台机器上安装nginx,安装步骤省略
安装完成后修改nginx默认页面为不同的内容
然后访问 http://192.168.31.100
默认应该显示192.168.31.186的内容
然后 重启192.168.31.186或停止192.168.31.186的keepalived 服务
这刷新页面
显示的是192.168.31.110的内容
如果192.168.31.186恢复正常vip会切回到192.168.31.186上
监控http服务
修改配置文件
vim /etc/keepalived/keepalived.conf
global_defs { router_id master }
vrrp_script chk_nginx_port { script "/check_nginx.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 1111 }
virtual_ipaddress { 192.168.31.100 }
track_script { chk_nginx_port }
}
vim /check_nginx.sh
#!/bin/bash
V_NUM=`eval "netstat -nlpt | grep '80' | wc -l"`
if [ $V_NUM -lt 1 ];then
/etc/init.d/keepalived stop
exit
fi
检查80端口如果没监听,就停止keepalived服务,vip就转到192.168.31.110上
这时就需要人为的修复http服务,然后重启keepalived服务