Nginx + Keepalived 实现站点高可用

概念和理论百度已经介绍得够全面了,这次来说说如何快速配置并生效。

Keepalive 配置

/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
! Configuration File for keepalived

vrrp_script chk_nginx {
# 检查脚本路径
script "bash /etc/keepalived/check_nginx.sh"
interval 2
weight -5
fall 3
rise 2
}

vrrp_instance VI_1 {
# 设定主从,第二台设置为 BACKUP
state MASTER
interface eth0
# 主机 IP
mcast_src_ip 10.0.125.156
virtual_router_id 51
# 权重,越大优先级越高
# BACKUP 设置为 99
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
# VIP
10.0.125.158
}
track_script {
chk_nginx
}
}

chk_nginx 脚本

/etc/keepalived/check_nginx.sh

1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
counter=$(ps -C nginx --no-heading|wc -l)
if [ "${counter}" = "0" ]; then
# 根据自身情况设定
/usr/local/nginx/sbin/nginx -s start
sleep 2
counter=$(ps -C nginx --no-heading|wc -l)
if [ "${counter}" = "0" ]; then
/etc/init.d/keepalived stop
fi
fi

配置完成后重启 keepalived 即可。