Nginx 反向代理高可用配置:负载均衡与故障转移实战

Nginx Reverse Proxy High Availability: Load Balancing and Failover in Practice

| iDev Team | 2026-08-02T09:00:00

Nginx 不仅是静态文件服务器,更是高性能反向代理的首选。本文以实战为主,介绍如何配置 Nginx 实现高可用的负载均衡和自动故障转移。

Nginx is not just a static file server but the go-to high-performance reverse proxy. This practical guide covers how to configure Nginx for high-availability load balancing and automatic failover.

基础负载均衡最简单的负载均衡配置——轮询(Round Robin):upstream backend { server 192.168.1.10:8080; server 192.168.1.11:8080; server 192.168.1.12:8080; } server { listen 80; location / { proxy_pass http://backend; } }加权负载均衡当服务器配置不同时,使用权重分配流量:upstream backend { server 192.168.1.10:8080 weight=5; # 高配服务器 server 192.168.1.11:8080 weight=3; server 192.168.1.12:8080 weight=2; }健康检查与故障转移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; # 备用服务器 }当某台服务器在 30 秒内失败 3 次,自动将其标记为不可用。backup 服务器仅在所有主服务器不可用时启用。IP Hash(会话保持)upstream backend { ip_hash; server 192.168.1.10:8080; server 192.168.1.11:8080; }同一 IP 的请求始终路由到同一后端,适合有状态应用。实际部署建议配合 Keepalived 实现 Nginx 自身的高可用使用 proxy_next_upstream 配置自动重试设置合理的 proxy_connect_timeout 和 proxy_read_timeout启用 access_log 和 error_log 以便故障排查


Basic Load BalancingThe simplest load balancing configuration — Round Robin:upstream backend { server 192.168.1.10:8080; server 192.168.1.11:8080; server 192.168.1.12:8080; } server { listen 80; location / { proxy_pass http://backend; } }Weighted Load BalancingWhen servers have different specs, use weights to distribute traffic:upstream backend { server 192.168.1.10:8080 weight=5; # High-spec server server 192.168.1.11:8080 weight=3; server 192.168.1.12:8080 weight=2; }Health Checks and Failoverupstream 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; # Backup server }When a server fails 3 times within 30 seconds, it's automatically marked as unavailable. The backup server activates only when all primary servers are down.IP Hash (Session Persistence)upstream backend { ip_hash; server 192.168.1.10:8080; server 192.168.1.11:8080; }Requests from the same IP always route to the same backend, suitable for stateful applications.Deployment RecommendationsUse Keepalived for Nginx's own high availabilityConfigure proxy_next_upstream for automatic retriesSet appropriate proxy_connect_timeout and proxy_read_timeout valuesEnable access_log and error_log for troubleshooting

← Back to News