Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 代理伺服器

Nginx Upstream 負載均衡五大分配策略詳解與實戰配置

編輯:代理伺服器

Nginx Upstream 支援 5 種分配方式

1. 輪詢 — 預設

請求按時間順序依序分派至後端伺服器,自動剔除 Down 機器。

upstream backend {
    server 192.168.0.14;
    server 192.168.0.15;
}

2. 權重

weight 越高分派機率越大,適用效能不均後端。

upstream backend {
    server 192.168.0.14 weight=10;
    server 192.168.0.15 weight=10;
}

3. IP Hash — 解決 Session 黏滯

依客戶端 IP 雜湊分派,同一 IP 固定命中同一後端,保持 Session 一致性 (無需共享 Session 儲存)。

upstream backend {
    ip_hash;
    server 192.168.0.14:88;
    server 192.168.0.15:80;
}

4. Fair (第三方模組) — 依回應時間動態分配

回應快的優先分派,實現「能者多勞」。需編譯 nginx-upstream-fair 模組。

upstream backend {
    server server1;
    server server2;
    fair;
}

5. URL Hash (第三方模組) — 針對快取優化

依請求 URL 雜湊分派,相同 URL 固定命中同一後端,提升後端快取命中率。需 ngx_http_upstream_consistent_hash 或類似模組。

upstream backend {
    server squid1:3128;
    server squid2:3128;
    hash $request_uri;
    hash_method crc32;
}

伺服器狀態參數 (通用)

參數說明
down暫時移出負載均衡 (維護用)
weight=N權重,預設 1,越大分派越多
max_fails=N允許失敗次數,預設 1,超過視為 Down
fail_timeout=Ns失敗後暫停時間,預設 10s
backup備用機,所有非 backup 機 Down/忙才啟用,壓力最小

綜合實戰範例

upstream backend {
    ip_hash;
    server 127.0.0.1:9090 down;           # 維護中
    server 127.0.0.1:8080 weight=2;       # 主力,雙倍權重
    server 127.0.0.1:6060;                # 正常
    server 127.0.0.1:7070 backup;         # 備用
}

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

進階功能提示

  • 多 Upstream 群組:可定義多個 upstream 區塊,不同 location 套用不同群組。
  • 請求體記錄除錯:client_body_in_file_only on + client_body_temp_path /path 1 2 3 (最多 3 層目錄)
  • URL 重寫/代理:location 正則匹配 → rewrite 或 proxy_pass 實現七層路由

選擇策略決策樹

  1. 後端無狀態 (無 Session/共享 Session) → 輪詢/權重
  2. 後端有狀態且難共享 Session → IP Hash
  3. 後端效能差異大、動態調度 → Fair (需第三方模組)
  4. 後端為快取伺服器 (Squid/Varnish) → URL Hash (需第三方模組)
  5. 需維護窗口/災備 → 善用 down/backup

結語

Nginx Upstream 內建輪詢/權重/IP Hash 三大核心策略已覆蓋 90%+ 場景。Fair/URL Hash 依賴第三方模組,引入前請評估維護成本。善用 weight/down/backup/max_fails/fail_timeout 微調,構建高可用、高效能的負載均衡層。

Copyright © Windows教程網 All Rights Reserved