在Linux上配置高可用的Nginx反向代理,通常需要结合负载均衡器、健康检查和故障转移机制。以下是分步方案:
# Ubuntu/Debian
sudo apt update && sudo apt install nginx -y
# CentOS/RHEL
sudo yum install epel-release -y
sudo yum install nginx -y
编辑主配置文件(示例):
# /etc/nginx/nginx.conf
http {
upstream backend {
server 192.168.1.10:80; # 后端服务器1
server 192.168.1.11:80; # 后端服务器2
}
server {
listen 80;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
}
}
}
bash
sudo apt install keepalived -y # 或 yum install keepalived
/etc/keepalived/keepalived.conf
):
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/24 # 虚拟IP(VIP)
}
}
state
和priority
):
conf
state BACKUP
priority 50
sudo systemctl enable --now nginx keepalived
sudo apt install haproxy -y # 或 yum install haproxy
/etc/haproxy/haproxy.cfg
)frontend http_front
bind *:80
default_backend http_back
backend http_back
balance roundrobin
server nginx1 192.168.1.10:80 check
server nginx2 192.168.1.11:80 check
健康检查:
nginx_upstream_check_module
或第三方工具(如Prometheus)实现。conf
option httpchk GET /health
server nginx1 192.168.1.10:80 check fall 3 rise 2
会话保持:
upstream backend {
ip_hash; # 基于IP的会话保持
server 192.168.1.10:80;
}
日志监控:
nginx
log_format proxy_log '$remote_addr - $upstream_addr - $request_time';
access_log /var/log/nginx/proxy.log proxy_log;
安全加固:
nginx
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
bash
ping 192.168.1.100 # 停止主节点Keepalived,观察VIP是否迁移
bash
curl -I http://VIP # 观察负载均衡是否剔除故障节点
# Nginx状态
sudo systemctl status nginx
sudo tail -f /var/log/nginx/error.log
# Keepalived日志
journalctl -u keepalived -f
# HAProxy统计页面
echo "show stat" | sudo socat /var/run/haproxy.sock stdio
通过上述方案,可实现99.9%以上的可用性。根据实际需求选择方案一(轻量级)或方案二(企业级)。云环境直接使用托管服务(如ALB)更便捷。