keepalived实现nginx高可用

准备两台机器100和150,100作为master,150作为backup

关闭防火墙和SELinux

两台机器上都执行yum install -y keepalived

两台机器上都安装上nginx,其中150上已经编译安装过nginx,100上需要yum安装nginx:yum install -y nginx

设定vip为120

编辑100(master)上的keepalived配置文件,vi /etc/keepalived/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
global_defs {
notification_email {
hubin@hubin.info
}
notification_email_from root@hubin.info
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id LVS_DEVEL
}

vrrp_script chk_nginx {
script "/usr/local/sbin/check_ng.sh"
interval 3
}

vrrp_instance VI_1 {
state MASTER
interface ens33
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass hubin>info
}
virtual_ipaddress {
192.168.88.120
}

track_script {
chk_nginx
}

}

编辑100(master)上的监控脚本,vi /usr/local/sbin/check_ng.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
#时间变量,用于记录日志
d=`date --date today +%Y%m%d_%H:%M:%S`
#计算nginx进程数量
n=`ps -C nginx --no-heading|wc -l`
#如果进程为0,则启动nginx,并且再次检测nginx进程数量,
#如果还为0,说明nginx无法启动,此时需要关闭keepalived
if [ $n -eq "0" ]; then
systemctl nginx start
n2=`ps -C nginx --no-heading|wc -l`
if [ $n2 -eq "0" ]; then
echo "$d nginx down,keepalived will stop" >> /var/log/check_ng.log
systemctl stop keepalived
fi
fi

给脚本执行权限,chmod +x check_ng.sh

编辑150(backup)上配置文件,vi /etc/keepalived/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
global_defs {
notification_email {
hubin@hubin.info
}
notification_email_from root@hubin.info
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id LVS_DEVEL
}

vrrp_script chk_nginx {
script "/usr/local/sbin/check_ng.sh"
interval 3
}

vrrp_instance VI_1 {
state BACKUP
interface ens33
virtual_router_id 51
priority 90
advert_int 1
authentication {
auth_type PASS
auth_pass hubin>info
}
virtual_ipaddress {
192.168.88.120
}

track_script {
chk_nginx
}

}

编辑150(backup)上监控脚本,vi /usr/local/sbin/check_ng.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
#时间变量,用于记录日志
d=`date --date today +%Y%m%d_%H:%M:%S`
#计算nginx进程数量
n=`ps -C nginx --no-heading|wc -l`
#如果进程为0,则启动nginx,并且再次检测nginx进程数量,
#如果还为0,说明nginx无法启动,此时需要关闭keepalived
if [ $n -eq "0" ]; then
/etc/init.d/nginx start
n2=`ps -C nginx --no-heading|wc -l`
if [ $n2 -eq "0" ]; then
echo "$d nginx down,keepalived will stop" >> /var/log/check_ng.log
systemctl stop keepalived
fi
fi

脚本加上可执行权限,chmod +x check_ng.sh

测试高可用

两台nginx主页设置成不同的页面

关闭master上的keepalived服务,测试是否从backup访问

开启master上的keepalived服务,测试是否移回master访问

发表评论

电子邮件地址不会被公开。 必填项已用*标注

😉😐😡😈🙂😯🙁🙄😛😳😮:mrgreen:😆💡😀👿😥😎😕