引言

Nginx高可用是保证系统稳定性的关键。本文介绍Nginx高可用架构设计。

一、Keepalived主备切换

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
# 安装Keepalived
yum install keepalived

# 主节点配置 /etc/keepalived/keepalived.conf
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.1.100
}
}

# 备节点配置
vrrp_instance VI_1 {
state BACKUP
interface eth0
virtual_router_id 51
priority 90
# ... 其他配置相同
}

二、负载均衡配置

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
upstream backend {
# 轮询(默认)
server 192.168.1.10:8080;
server 192.168.1.11:8080;

# 加权轮询
server 192.168.1.10:8080 weight=3;
server 192.168.1.11:8080 weight=1;

# IP Hash
ip_hash;
server 192.168.1.10:8080;
server 192.168.1.11:8080;

# 最少连接
least_conn;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}

server {
listen 80;
server_name example.com;

location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}

三、健康检查

1
2
3
4
5
6
7
upstream backend {
server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 max_fails=3 fail_timeout=30s;

# 备用服务器
server 192.168.1.12:8080 backup;
}

四、监控脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
# check_nginx.sh

counter=0
while [ $counter -lt 3 ]; do
nginx_status=$(systemctl is-active nginx)
if [ "$nginx_status" = "active" ]; then
exit 0
fi
let counter++
sleep 1
done

# Nginx异常,停止Keepalived
systemctl stop keepalived

总结

Nginx高可用核心:

  1. Keepalived:主备切换
  2. 负载均衡:分流请求
  3. 健康检查:自动摘除故障节点
  4. 监控告警:及时发现问题

参考资料