Nginx 反向代理與負載均衡高級配置 2026 | 高性能高可用架構實戰

Nginx 作為最流行的反向代理和負載均衡器,其高級功能遠不止基礎的請求轉發。本文將深入 Nginx 負載均衡的核心特性,從負載均衡算法到健康檢查,從會話保持到限流緩存,全面掌握構建高性能高可用架構的實戰技能。
一、負載均衡基礎
1.1 負載均衡架構
客戶端請求
│
▼
┌─────────┐
│ Nginx │ ← 負載均衡器
└────┬────┘
│
├──→ 後端服務器 1 (192.168.1.101)
├──→ 後端服務器 2 (192.168.1.102)
└──→ 後端服務器 3 (192.168.1.103)1.2 基礎配置
http {
upstream backend {
server 192.168.1.101:8080;
server 192.168.1.102:8080;
server 192.168.1.103: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;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}二、5 種負載均衡算法
2.1 輪詢(Round Robin)— 默認
upstream backend {
server 192.168.1.101:8080;
server 192.168.1.102:8080;
server 192.168.1.103:8080;
}特點: 請求按順序逐一分配,默認算法。
2.2 加權輪詢(Weighted Round Robin)
upstream backend {
server 192.168.1.101:8080 weight=5; # 處理 50% 請求
server 192.168.1.102:8080 weight=3; # 處理 30% 請求
server 192.168.1.103:8080 weight=2; # 處理 20% 請求
}特點: 根據服務器性能分配不同權重,性能好的服務器多分請求。
2.3 IP 哈希(IP Hash)
upstream backend {
ip_hash;
server 192.168.1.101:8080;
server 192.168.1.102:8080;
server 192.168.1.103:8080;
}特點: 根據客戶端 IP 哈希分配,同一客戶端始終訪問同一服務器,實現簡單的會話保持。
2.4 最少連接(Least Connections)
upstream backend {
least_conn;
server 192.168.1.101:8080;
server 192.168.1.102:8080;
server 192.168.1.103:8080;
}特點: 將請求分配給當前連接數最少的服務器,適合請求處理時間差異大的場景。
2.5 最少時間(Least Time)— Nginx Plus
upstream backend {
least_time header; # 或 least_time last_byte
server 192.168.1.101:8080;
server 192.168.1.102:8080;
server 192.168.1.103:8080;
}特點: 選擇響應時間最短的服務器,需要 Nginx Plus 商業版。
三、服務器狀態管理
3.1 服務器狀態參數
upstream backend {
# 正常服務器
server 192.168.1.101:8080 weight=5 max_fails=3 fail_timeout=30s;
# 備用服務器(正常服務器都掛了才用)
server 192.168.1.102:8080 backup;
# 不可用(已下線)
server 192.168.1.103:8080 down;
# 最大連接數
server 192.168.1.104:8080 max_conns=100;
# 慢啟動(新加入的服務器逐漸增加流量)
server 192.168.1.105:8080 slow_start=30s;
}3.2 主動健康檢查 — Nginx Plus
upstream backend {
zone backend 64k;
server 192.168.1.101:8080;
server 192.168.1.102:8080;
server 192.168.1.103:8080;
}
server {
location / {
proxy_pass http://backend;
health_check interval=5s fails=3 passes=2 uri=/health match=health_ok;
}
match health_ok {
status 200;
body ~ '"status":"ok"';
}
}3.3 被動健康檢查 — 開源版
upstream backend {
server 192.168.1.101:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.102:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.103:8080 max_fails=3 fail_timeout=30s;
}
server {
location / {
proxy_pass http://backend;
proxy_next_upstream error timeout http_500 http_502 http_503;
proxy_connect_timeout 5s;
proxy_read_timeout 10s;
proxy_send_timeout 10s;
}
}proxy_next_upstream 參數說明:
error:連接錯誤或超時timeout:讀取/發送超時http_500:500 錯誤http_502:502 錯誤http_503:503 錯誤http_403:403 錯誤http_404:404 錯誤non_idempotent:非冪等請求也重試(POST 等,謹慎使用)
四、會話保持
4.1 Cookie 會話保持
upstream backend {
server 192.168.1.101:8080;
server 192.168.1.102:8080;
server 192.168.1.103:8080;
# 使用 cookie 實現會話粘性
sticky cookie srv_id expires=1h domain=.example.com path=/;
}4.2 route 方法會話保持
upstream backend {
server 192.168.1.101:8080 route=server1;
server 192.168.1.102:8080 route=server2;
sticky route $route_cookie $route_uri;
}
map $cookie_jsessionid $route_cookie {
~.+\.(?P<route>\w+)$ $route;
}4.3 learn 方法 — Nginx Plus
upstream backend {
server 192.168.1.101:8080;
server 192.168.1.102:8080;
sticky learn
create=$upstream_cookie_sessionid
lookup=$cookie_sessionid
zone=client_sessions:1m
timeout=1h;
}五、連接限流與速率限制
5.1 請求速率限制
http {
# 定義限流區域(按客戶端 IP)
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
server {
location /api/ {
# 應用限流,允許突發 20 個請求(nodelay 不延遲處理)
limit_req zone=req_limit burst=20 nodelay;
proxy_pass http://backend;
}
location /login/ {
# 登錄接口更嚴格的限流
limit_req zone=login_limit burst=5 nodelay;
limit_req_status 429;
proxy_pass http://backend;
}
}
# 登錄專用限流
limit_req_zone $binary_remote_addr zone=login_limit:10m rate=5r/m;
}5.2 連接數限制
http {
# 按 IP 限制連接數
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
location /download/ {
# 每個 IP 最多 10 個連接
limit_conn conn_limit 10;
limit_conn_status 429;
proxy_pass http://backend;
}
}
}5.3 帶寬限制
server {
location /download/ {
# 限制每個連接的傳輸速率
limit_rate 1m; # 1MB/s
limit_rate_after 10m; # 傳輸 10MB 後開始限速
proxy_pass http://backend;
}
}5.4 限流日誌配置
http {
limit_req_log_level warn;
limit_conn_log_level warn;
limit_rate 1m;
# 自定義錯誤頁面
error_page 429 /429.html;
location = /429.html {
root /usr/share/nginx/html;
internal;
}
}六、緩存配置
6.1 基礎緩存配置
http {
# 定義緩存區域
proxy_cache_path /var/cache/nginx
levels=1:2
keys_zone=my_cache:10m
max_size=10g
inactive=7d
use_temp_path=off;
server {
location /static/ {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_valid any 5m;
proxy_cache_key "$scheme$request_method$host$request_uri";
add_header X-Cache-Status $upstream_cache_status;
proxy_pass http://backend;
}
}
}6.2 緩存精細控制
http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=api_cache:10m max_size=10g;
server {
location /api/ {
proxy_cache api_cache;
# 只緩存 GET 和 HEAD 請求
proxy_cache_methods GET HEAD;
# 緩存響應碼
proxy_cache_valid 200 302 5m;
proxy_cache_valid 301 1h;
proxy_cache_valid 404 1m;
# 使用後端的 Cache-Control 頭
proxy_cache_valid any 1m;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503;
# 緩存鎖(防止緩存擊穿)
proxy_cache_lock on;
proxy_cache_lock_timeout 5s;
# 緩存鍵
proxy_cache_key "$host$request_uri$cookie_user_id";
# 添加緩存狀態頭
add_header X-Cache $upstream_cache_status;
proxy_pass http://backend;
}
}
}6.3 緩存清理
# 使用 proxy_cache_purge 模塊(需要編譯或 Nginx Plus)
server {
location ~ /purge(/.*) {
allow 127.0.0.1;
deny all;
proxy_cache_purge my_cache $scheme$request_method$host$1;
}
}七、WebSocket 代理
http {
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream ws_backend {
server 192.168.1.101:8080;
server 192.168.1.102:8080;
}
server {
listen 80;
server_name ws.example.com;
location /ws/ {
proxy_pass http://ws_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
# WebSocket 超時配置
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
proxy_connect_timeout 10s;
# 會話保持(WebSocket 需要)
proxy_set_header X-Real-IP $remote_addr;
}
}
}八、gRPC 代理
http {
upstream grpc_backend {
server 192.168.1.101:50051;
server 192.168.1.102:50051;
}
server {
listen 443 ssl http2;
server_name grpc.example.com;
ssl_certificate /etc/nginx/ssl/server.crt;
ssl_certificate_key /etc/nginx/ssl/server.key;
location / {
grpc_pass grpc://grpc_backend;
# gRPC 超時
grpc_read_timeout 300s;
grpc_send_timeout 300s;
# gRPC 響應頭
grpc_set_header X-Real-IP $remote_addr;
# 流式 RPC 支持
grpc_buffer_size 64k;
}
}
}九、四層負載均衡(TCP/UDP)
# /etc/nginx/nginx.conf — 需要在 stream 塊中配置
stream {
# TCP 負載均衡
upstream mysql_cluster {
server 192.168.1.101:3306 weight=5;
server 192.168.1.102:3306 weight=5;
server 192.168.1.103:3306 backup;
}
upstream redis_cluster {
server 192.168.1.101:6379;
server 192.168.1.102:6379;
hash $remote_addr consistent;
}
server {
listen 3306;
proxy_pass mysql_cluster;
proxy_connect_timeout 3s;
proxy_timeout 30s;
}
server {
listen 6379;
proxy_pass redis_cluster;
}
# UDP 負載均衡
upstream dns_servers {
server 8.8.8.8:53;
server 8.8.4.4:53;
}
server {
listen 53 udp;
proxy_pass dns_servers;
proxy_timeout 5s;
}
}
http {
# HTTP 配置...
}十、生產環境最佳實踐
10.1 完整生產配置示例
user nginx;
worker_processes auto;
worker_rlimit_nofile 65535;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 65535;
use epoll;
multi_accept on;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 日誌格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'$request_time $upstream_response_time';
access_log /var/log/nginx/access.log main;
# 基礎優化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# Gzip 壓縮
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss;
# 限流配置
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
# 緩存配置
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=static_cache:100m max_size=10g inactive=7d;
# 上游服務器
upstream app_backend {
least_conn;
server 192.168.1.101:8080 weight=5 max_fails=3 fail_timeout=30s;
server 192.168.1.102:8080 weight=5 max_fails=3 fail_timeout=30s;
server 192.168.1.103:8080 weight=3 max_fails=3 fail_timeout=30s backup;
keepalive 64;
}
# HTTP 重定向到 HTTPS
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$server_name$request_uri;
}
# HTTPS 主配置
server {
listen 443 ssl http2;
server_name example.com www.example.com;
# SSL 配置
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# 安全頭
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# 靜態文件緩存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
proxy_cache static_cache;
proxy_cache_valid 200 30d;
proxy_cache_valid 404 1m;
expires 30d;
add_header Cache-Control "public, immutable";
proxy_pass http://app_backend;
}
# API 接口
location /api/ {
limit_req zone=api_limit burst=200 nodelay;
limit_conn conn_limit 50;
proxy_pass http://app_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 5s;
proxy_read_timeout 30s;
proxy_send_timeout 30s;
proxy_next_upstream error timeout http_500 http_502 http_503;
proxy_next_upstream_tries 2;
}
# 根路徑
location / {
proxy_pass http://app_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}
}10.2 Nginx 狀態監控
server {
listen 8080;
server_name localhost;
# 基礎狀態頁
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
# Nginx Plus 狀態 API
location /api/ {
api write=off;
allow 127.0.0.1;
deny all;
}
}十一、高可用架構
11.1 Nginx 主備模式(Keepalived)
# 安裝 Keepalived
apt 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 secret123
}
virtual_ipaddress {
192.168.1.100
}
track_script {
chk_nginx
}
}
vrrp_script chk_nginx {
script "/etc/keepalived/check_nginx.sh"
interval 2
weight -20
}# /etc/keepalived/check_nginx.sh
#!/bin/bash
if [ "$(pidof nginx | wc -w)" -eq 0 ]; then
exit 1
else
exit 0
fi十二、總結
- ✅ 掌握 5 種負載均衡算法(輪詢、加權、IP哈希、最少連接、最少時間)
- ✅ 服務器狀態管理與健康檢查
- ✅ 會話保持實現(Cookie、route、learn)
- ✅ 連接限流與速率限制
- ✅ Nginx 緩存配置與管理
- ✅ WebSocket 和 gRPC 代理
- ✅ 四層負載均衡(TCP/UDP)
- ✅ 生產環境完整配置
- ✅ 高可用架構(Keepalived 主備)
Nginx 負載均衡是構建高性能高可用系統的基石,掌握這些高級配置,讓你的架構更加穩定和高效。
相關閱讀: