一.介绍
编写脚本,keepalived是根据返回值判断的,所以这里直接grep进程名,能查到返回0,否则返回1
让keepalived每5秒运行一次脚本,2次都返回1则认为httpd服务挂掉了,则降低优先级,释放vip。
有的博客例子是脚本检测服务有问题,直接关闭keepalived,这样其实很麻烦,而且当台机器有多个实例都要高可用,就没法这么做了。
二.配置
环境声明
[web-server-1]
主机名 = host-1
系统 = centos-7.3
地址 = 192.168.2.41
软件 = keepalived-1.3.5
httpd-2.4.6
[web-server-2]
主机名 = host-2
系统 = centos-7.3
地址 = 192.168.2.150
软件 = keepalived-1.3.5
httpd-2.4.6
服务配置
1.已经有其他需要高可用服务,可以不安装,这里只是做测试
(机器均操作)yum -y install httpd
systemctl start httpd
yum -y install keepalived
systemctl enable keepalived
2.添加测试文件
(host-1操作)
echo "one" > /var/www/html/index.html
(host-2操作)
echo "tow" > /var/www/html/index.html
3.创建检测脚本
(机器均操作)vim /etc/keepalived/check_httpd.sh
#!/bin/sh
A=`ps -C nginx --no-header |wc -l`
if [ $A -eq 0 ]
then
exit 1
fi
chmod +x /etc/keepalived/check_httpd.sh
4.修改配置文件如下,多余的删除
(host-1操作)vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
router_id lb01
}
vrrp_script httpd #vrrp脚本命名
{
script "/etc/keepalived/check_httpd.sh" #要执行的脚本
interval 2 #脚本指定间隔
weight -40 #优先级(如果脚本执行结果为0,并且weight配置的值大于0,则优先级相应的增加,如果脚本执行结果非0,并且weight配置的值小于0,则优先级相应的减少)
}
vrrp_instance VI_1 {
state MASTER
interface enp0s8
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script #调用上面定义的检查脚本
{
httpd
}
virtual_ipaddress {
192.168.2.99
}
}
(host-2操作)vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
router_id lb02
}
vrrp_script httpd
{
script "/etc/keepalived/check_httpd.sh"
interval 2
weight 2
}
vrrp_instance VI_1 {
state BACKUP
interface enp0s8
virtual_router_id 51
priority 90
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script
{
httpd
}
virtual_ipaddress {
192.168.2.99
}
}
(机器均操作)systemctl start keepalived
三.测试
最开始的99报错,是因为主节点还未运行脚本检测,等待10秒将切换。这个时间在生产环境无意是非常长的,可以适当调节短。
四.多实例
每一段vrrp_instrance都是一个,底下的看起来没什么不同,但是可以配置脚本,让VI_1检测到nginx有问题后,将10.0.0.3下线
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 150
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
10.0.0.3/24 dev eth0 label eth0:1
}
}
vrrp_instance VI_2 {
state BACKUP
interface eth0
virtual_router_id 52
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
10.0.0.4/24 dev eth0 label eth0:2
}
}