问题描述

Keepalived不容易挂掉,容易挂掉的是Nginx,如果Nginx挂掉了依然可以通过Keepalived访问机器,但是访问不到Nginx服务。所以这里需要借助Keepalived的vrrp_script配置来调用自定义shell脚本,来检测Nginx是否挂掉,如果Nginx挂掉了,就启动它,打开失败就关闭Keepalived启用备用机

实现过程

编写shell脚本

在 / 目录下新建shell目录存放shell脚本文件

1
mkdir /shell

新建 .sh文件,命名为:nginx_check.sh,内容如下:(该脚本的功能为通过 ps -ef|grep -w nginx|grep -v grep|wc -l查看当前有多少个Nginx服务在运行,如果返回0说明Nginx服务没有运行,就启动Nginx,过2秒再查看是否启动成功,启动失败就停止Keepalived启用备用机)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/bin/bash

echo 'check Nginx'

count_nginx=`ps -ef|grep -w nginx|grep -v grep|wc -l`

echo $count_nginx

if [ $count_nginx -eq 0 ];then

systemctl start nginx
echo 'start Nginx'
sleep 2

if [ `ps -ef|grep -w nginx|grep -v grep|wc -l` -eq 0 ];then
echo 'stop keepalived'
systemctl stop keepalived
fi

fi

修改Keepalived配置

配置文件路径为:/etc/keepalived/keepalived.conf

添加节点:

1
2
3
4
5
vrrp_script check_nginx {
script "/shell/nginx_check.sh"
nterval 2
weight -20
}

在vrrp_instance VI_1节点添加:

1
2
3
track_script {
check_nginx
}

完整keepalived.conf如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
! Configuration File for keepalived

global_defs {
notification_email {
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 192.168.200.1
smtp_connect_timeout 30
router_id KEEPALIVED_NGINX_MASTER
vrrp_skip_check_adv_addr
# vrrp_strict
vrrp_garp_interval 0
vrrp_gna_interval 0
}

vrrp_script check_nginx {
script "/shell/nginx_check.sh"
nterval 2
weight -20
}

vrrp_instance VI_1 {
state MASTER
interface ens33
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
check_nginx
}
virtual_ipaddress {
192.168.1.99
}
}

重启Keepalived服务

1
systemctl restart keepalived

测试

关闭Nginx服务

1
systemctl stop nginx

等2秒查看Nginx服务状态:Nginx服务正在运行

1
systemctl status nginx

PS.

我在测试时keepalived vrrp_script始终不起作用,通过网上的解决方案也没有解决,所以我就不使用vrrp_script了,转而使用Linux的Crontab定时任务定时执行检测脚本,如何使用Crontab查看博客:CentOS7使用Crontab定时任务

如果你解决了keepalived vrrp_script不起作用,请在评论区留言一下,谢谢(~ ̄▽ ̄)~