Nginx中多種負(fù)載均衡策略配置的實(shí)戰(zhàn)指南
前言
在當(dāng)今高并發(fā)、大流量的互聯(lián)網(wǎng)應(yīng)用中,單臺(tái)服務(wù)器往往難以承受巨大的訪問壓力。負(fù)載均衡作為解決這一問題的關(guān)鍵技術(shù),能夠?qū)⒄?qǐng)求分發(fā)到多臺(tái)服務(wù)器上,實(shí)現(xiàn)系統(tǒng)的高可用性和高性能。
Nginx作為業(yè)界領(lǐng)先的Web服務(wù)器和反向代理服務(wù)器,其負(fù)載均衡功能強(qiáng)大且配置靈活,被廣泛應(yīng)用于各大互聯(lián)網(wǎng)公司。本文將深入探討Nginx負(fù)載均衡的各種策略和配置方法,通過實(shí)際案例幫助你掌握負(fù)載均衡的核心技能。
一、負(fù)載均衡基礎(chǔ)概念
1.1 什么是負(fù)載均衡
負(fù)載均衡(Load Balancing)是一種將網(wǎng)絡(luò)請(qǐng)求分配到多個(gè)服務(wù)器的技術(shù),主要目的是:
核心目標(biāo):
- 高可用性:避免單點(diǎn)故障,提高系統(tǒng)可靠性
- 高性能:分散請(qǐng)求壓力,提升系統(tǒng)處理能力
- 可擴(kuò)展性:支持水平擴(kuò)展,便于系統(tǒng)擴(kuò)容
- 靈活性:支持動(dòng)態(tài)調(diào)整和灰度發(fā)布
工作原理:
客戶端 → 負(fù)載均衡器 → 后端服務(wù)器集群
↓
服務(wù)器1
服務(wù)器2
服務(wù)器3
1.2 負(fù)載均衡類型
硬件負(fù)載均衡
- F5 BIG-IP:企業(yè)級(jí)硬件負(fù)載均衡器
- A10:高性能負(fù)載均衡設(shè)備
- Citrix NetScaler:應(yīng)用交付控制器
優(yōu)點(diǎn):
- 性能強(qiáng)大,處理能力高
- 功能完善,支持復(fù)雜算法
- 穩(wěn)定性好,可靠性高
缺點(diǎn):
- 價(jià)格昂貴,成本高
- 配置復(fù)雜,需要專業(yè)維護(hù)
- 擴(kuò)展性差,升級(jí)困難
軟件負(fù)載均衡
- Nginx:高性能Web服務(wù)器和反向代理
- HAProxy:高可用性負(fù)載均衡器
- LVS:Linux虛擬服務(wù)器
- Apache mod_proxy_balancer:Apache模塊
優(yōu)點(diǎn):
- 成本低廉,開源免費(fèi)
- 配置靈活,易于擴(kuò)展
- 社區(qū)活躍,支持豐富
缺點(diǎn):
- 性能相對(duì)硬件較低
- 功能相對(duì)簡(jiǎn)單
- 需要自己維護(hù)高可用
1.3 Nginx負(fù)載均衡優(yōu)勢(shì)
技術(shù)優(yōu)勢(shì):
- 高性能:基于事件驅(qū)動(dòng)架構(gòu),支持?jǐn)?shù)萬并發(fā)連接
- 高可用性:支持健康檢查和故障轉(zhuǎn)移
- 靈活性:支持多種負(fù)載均衡算法
- 擴(kuò)展性:支持第三方模塊擴(kuò)展
功能優(yōu)勢(shì):
- 七層負(fù)載均衡:支持HTTP/HTTPS協(xié)議
- 四層負(fù)載均衡:支持TCP/UDP協(xié)議
- SSL終止:支持SSL證書卸載
- 緩存功能:支持內(nèi)容緩存
- 壓縮功能:支持Gzip壓縮
二、Nginx負(fù)載均衡基礎(chǔ)配置
2.1 upstream模塊詳解
upstream基本語法
# =============================================
# upstream模塊基礎(chǔ)配置
# =============================================
# 定義后端服務(wù)器組
upstream backend_servers {
# 服務(wù)器地址和端口
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
# 負(fù)載均衡方法
# 默認(rèn)為輪詢(round-robin)
# least_conn; # 最少連接
# ip_hash; # IP哈希
# hash $request_uri; # 一致性哈希
}
server {
listen 80;
server_name lb.example.com;
location / {
# 代理到后端服務(wù)器組
proxy_pass http://backend_servers;
# 設(shè)置代理頭信息
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;
}
}
upstream參數(shù)詳解
# =============================================
# upstream服務(wù)器參數(shù)詳解
# =============================================
upstream backend_servers {
# 基本服務(wù)器配置
server 192.168.1.10:8080 weight=5 max_fails=3 fail_timeout=30s backup;
server 192.168.1.11:8080 weight=3 max_fails=3 fail_timeout=30s;
server 192.168.1.12:8080 weight=2 max_fails=3 fail_timeout=30s down;
# 服務(wù)器參數(shù)說明:
# weight: 權(quán)重,數(shù)值越大分配到的請(qǐng)求越多
# max_fails: 最大失敗次數(shù),超過則標(biāo)記為不可用
# fail_timeout: 失敗超時(shí)時(shí)間,單位秒
# backup: 備份服務(wù)器,主服務(wù)器都不可用時(shí)啟用
# down: 標(biāo)記服務(wù)器永久不可用
# max_conns: 最大連接數(shù)限制
# resolve: 動(dòng)態(tài)解析域名
# service: 服務(wù)發(fā)現(xiàn)配置
# slow_start: 慢啟動(dòng)時(shí)間
# 負(fù)載均衡方法
least_conn;
# 連接保持配置
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
# 會(huì)話保持配置
sticky cookie srv_id expires=1h domain=.example.com path=/;
# 健康檢查配置
health_check interval=10s fails=3 passes=2 uri=/health port=8080;
}
2.2 基礎(chǔ)負(fù)載均衡配置
簡(jiǎn)單輪詢負(fù)載均衡
# =============================================
# 簡(jiǎn)單輪詢負(fù)載均衡配置
# =============================================
# 定義后端服務(wù)器組(輪詢方式)
upstream backend_round_robin {
# 輪詢方式(默認(rèn))
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
# 連接保持配置
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
server {
listen 80;
server_name round-robin.example.com;
access_log /var/log/nginx/round-robin.example.com.access.log main;
error_log /var/log/nginx/round-robin.example.com.error.log warn;
location / {
# 代理到后端服務(wù)器組
proxy_pass http://backend_round_robin;
# 設(shè)置代理頭信息
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;
# 連接設(shè)置
proxy_http_version 1.1;
proxy_set_header Connection "";
# 超時(shí)設(shè)置
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 緩沖區(qū)設(shè)置
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;
# 添加負(fù)載均衡信息到響應(yīng)頭
add_header X-Upstream-Addr $upstream_addr;
add_header X-Upstream-Response-Time $upstream_response_time;
}
# =============================================
# 健康檢查端點(diǎn)
# =============================================
location /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
}
帶權(quán)重輪詢負(fù)載均衡
# =============================================
# 帶權(quán)重輪詢負(fù)載均衡配置
# =============================================
# 定義后端服務(wù)器組(加權(quán)輪詢)
upstream backend_weighted {
# 權(quán)重分配,數(shù)值越大分配到的請(qǐng)求越多
server 192.168.1.10:8080 weight=5; # 50%的請(qǐng)求
server 192.168.1.11:8080 weight=3; # 30%的請(qǐng)求
server 192.168.1.12:8080 weight=2; # 20%的請(qǐng)求
# 健康檢查設(shè)置
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 max_fails=3 fail_timeout=30s;
# 連接保持
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
server {
listen 80;
server_name weighted.example.com;
access_log /var/log/nginx/weighted.example.com.access.log main;
error_log /var/log/nginx/weighted.example.com.error.log warn;
location / {
proxy_pass http://backend_weighted;
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 "";
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;
# 添加權(quán)重信息到響應(yīng)頭
add_header X-Upstream-Addr $upstream_addr;
add_header X-Upstream-Weight "5:3:2";
add_header X-Upstream-Response-Time $upstream_response_time;
}
# =============================================
# 負(fù)載均衡統(tǒng)計(jì)
# =============================================
location /lb_stats {
# 限制訪問
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
# 顯示負(fù)載均衡統(tǒng)計(jì)信息
add_header Content-Type "application/json";
return 200 '{
"algorithm": "weighted_round_robin",
"servers": [
{"addr": "192.168.1.10:8080", "weight": 5, "status": "up"},
{"addr": "192.168.1.11:8080", "weight": 3, "status": "up"},
{"addr": "192.168.1.12:8080", "weight": 2, "status": "up"}
]
}';
}
}
三、負(fù)載均衡策略詳解
3.1 輪詢策略(Round Robin)
基礎(chǔ)輪詢配置
# =============================================
# 輪詢策略配置
# =============================================
# 定義后端服務(wù)器組(輪詢)
upstream backend_round_robin {
# 輪詢方式(默認(rèn))
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
# 健康檢查
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 max_fails=3 fail_timeout=30s;
# 連接保持
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
server {
listen 80;
server_name rr.example.com;
location / {
proxy_pass http://backend_round_robin;
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 "";
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 添加輪詢信息
add_header X-LB-Algorithm "round_robin";
add_header X-Upstream-Addr $upstream_addr;
}
}
輪詢策略特點(diǎn)
工作原理:
- 按照順序?qū)⒄?qǐng)求依次分配到后端服務(wù)器
- 第一個(gè)請(qǐng)求分配到服務(wù)器1,第二個(gè)到服務(wù)器2,以此類推
- 循環(huán)往復(fù),實(shí)現(xiàn)均勻分配
適用場(chǎng)景:
- 后端服務(wù)器性能相近
- 請(qǐng)求處理時(shí)間相似
- 不需要會(huì)話保持
優(yōu)缺點(diǎn):
- ? 配置簡(jiǎn)單,易于理解
- ? 請(qǐng)求分配均勻
- ? 不考慮服務(wù)器性能差異
- ? 不考慮當(dāng)前連接數(shù)
3.2 加權(quán)輪詢策略(Weighted Round Robin)
加權(quán)輪詢配置
# =============================================
# 加權(quán)輪詢策略配置
# =============================================
# 定義后端服務(wù)器組(加權(quán)輪詢)
upstream backend_weighted {
# 權(quán)重分配
server 192.168.1.10:8080 weight=5; # 高性能服務(wù)器
server 192.168.1.11:8080 weight=3; # 中等性能服務(wù)器
server 192.168.1.12:8080 weight=2; # 低性能服務(wù)器
# 健康檢查
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 max_fails=3 fail_timeout=30s;
# 連接保持
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
server {
listen 80;
server_name wrr.example.com;
location / {
proxy_pass http://backend_weighted;
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 "";
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 添加權(quán)重信息
add_header X-LB-Algorithm "weighted_round_robin";
add_header X-Upstream-Addr $upstream_addr;
add_header X-Upstream-Weight "5:3:2";
}
}
加權(quán)輪詢策略特點(diǎn)
工作原理:
- 根據(jù)服務(wù)器權(quán)重分配請(qǐng)求
- 權(quán)重越高,分配到的請(qǐng)求越多
- 權(quán)重比例為5:3:2,則請(qǐng)求分配比例約為50%:30%:20%
適用場(chǎng)景:
- 后端服務(wù)器性能差異較大
- 服務(wù)器配置不同
- 需要根據(jù)性能分配負(fù)載
優(yōu)缺點(diǎn):
- ? 考慮服務(wù)器性能差異
- ? 靈活配置負(fù)載分配
- ? 優(yōu)化資源利用率
- ? 需要手動(dòng)調(diào)整權(quán)重
- ? 不考慮實(shí)時(shí)負(fù)載情況
3.3 IP哈希策略(IP Hash)
IP哈希配置
# =============================================
# IP哈希策略配置
# =============================================
# 定義后端服務(wù)器組(IP哈希)
upstream backend_ip_hash {
# IP哈希方式,確保同一客戶端請(qǐng)求始終轉(zhuǎn)發(fā)到同一服務(wù)器
ip_hash;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
# 健康檢查
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 max_fails=3 fail_timeout=30s;
# 連接保持
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
server {
listen 80;
server_name iphash.example.com;
location / {
proxy_pass http://backend_ip_hash;
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 "";
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 添加哈希信息
add_header X-LB-Algorithm "ip_hash";
add_header X-Upstream-Addr $upstream_addr;
add_header X-Client-IP $remote_addr;
}
}
IP哈希策略特點(diǎn)
工作原理:
- 基于客戶端IP地址計(jì)算哈希值
- 同一IP的請(qǐng)求始終分配到同一服務(wù)器
- 確保會(huì)話一致性
適用場(chǎng)景:
- 需要會(huì)話保持
- 使用本地會(huì)話存儲(chǔ)
- 無分布式會(huì)話
優(yōu)缺點(diǎn):
- ? 會(huì)話保持,用戶體驗(yàn)好
- ? 配置簡(jiǎn)單
- ? 負(fù)載分配不均勻
- ? 服務(wù)器故障時(shí)影響大
- ? 不支持動(dòng)態(tài)添加服務(wù)器
3.4 最少連接策略(Least Connections)
最少連接配置
# =============================================
# 最少連接策略配置
# =============================================
# 定義后端服務(wù)器組(最少連接)
upstream backend_least_conn {
# 最少連接方式,將請(qǐng)求轉(zhuǎn)發(fā)到連接數(shù)最少的服務(wù)器
least_conn;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
# 健康檢查
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 max_fails=3 fail_timeout=30s;
# 連接保持
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
server {
listen 80;
server_name leastconn.example.com;
location / {
proxy_pass http://backend_least_conn;
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 "";
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 添加連接數(shù)信息
add_header X-LB-Algorithm "least_conn";
add_header X-Upstream-Addr $upstream_addr;
add_header X-Upstream-Connections $upstream_connections;
}
}
最少連接策略特點(diǎn)
工作原理:
- 實(shí)時(shí)監(jiān)控各服務(wù)器的連接數(shù)
- 將新請(qǐng)求分配到連接數(shù)最少的服務(wù)器
- 動(dòng)態(tài)調(diào)整負(fù)載分配
適用場(chǎng)景:
- 請(qǐng)求處理時(shí)間差異較大
- 需要?jiǎng)討B(tài)負(fù)載均衡
- 長(zhǎng)連接應(yīng)用
優(yōu)缺點(diǎn):
- ? 動(dòng)態(tài)負(fù)載均衡
- ? 響應(yīng)時(shí)間更優(yōu)
- ? 資源利用率高
- ? 需要實(shí)時(shí)監(jiān)控連接數(shù)
- ? 配置相對(duì)復(fù)雜
3.5 一致性哈希策略(Consistent Hash)
一致性哈希配置
# =============================================
# 一致性哈希策略配置
# =============================================
# 定義后端服務(wù)器組(一致性哈希)
upstream backend_consistent_hash {
# 一致性哈希方式
hash $request_uri consistent;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
# 健康檢查
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 max_fails=3 fail_timeout=30s;
# 連接保持
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
server {
listen 80;
server_name consistent.example.com;
location / {
proxy_pass http://backend_consistent_hash;
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 "";
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 添加哈希信息
add_header X-LB-Algorithm "consistent_hash";
add_header X-Upstream-Addr $upstream_addr;
add_header X-Hash-Key $request_uri;
}
}
一致性哈希策略特點(diǎn)
工作原理:
- 基于請(qǐng)求特征(如URI)計(jì)算哈希值
- 相同特征的請(qǐng)求分配到同一服務(wù)器
- 支持動(dòng)態(tài)添加/刪除服務(wù)器
適用場(chǎng)景:
- 緩存系統(tǒng)
- 分布式存儲(chǔ)
- 需要數(shù)據(jù)一致性
優(yōu)缺點(diǎn):
- ? 支持動(dòng)態(tài)擴(kuò)容
- ? 數(shù)據(jù)一致性好
- ? 負(fù)載分配相對(duì)均勻
- ? 配置復(fù)雜
- ? 需要選擇合適的哈希鍵
3.6 策略對(duì)比總結(jié)
| 策略 | 適用場(chǎng)景 | 優(yōu)點(diǎn) | 缺點(diǎn) |
|---|---|---|---|
| 輪詢 | 服務(wù)器性能相近 | 配置簡(jiǎn)單,分配均勻 | 不考慮性能差異 |
| 加權(quán)輪詢 | 服務(wù)器性能差異大 | 考慮性能差異 | 需要手動(dòng)調(diào)整權(quán)重 |
| IP哈希 | 需要會(huì)話保持 | 會(huì)話保持 | 負(fù)載不均勻 |
| 最少連接 | 請(qǐng)求處理時(shí)間差異大 | 動(dòng)態(tài)負(fù)載均衡 | 配置復(fù)雜 |
| 一致性哈希 | 緩存系統(tǒng) | 支持動(dòng)態(tài)擴(kuò)容 | 配置復(fù)雜 |
四、高級(jí)負(fù)載均衡配置
4.1 健康檢查配置
被動(dòng)健康檢查
# =============================================
# 被動(dòng)健康檢查配置
# =============================================
upstream backend_health_check {
# 后端服務(wù)器配置
server 192.168.1.10:8080 weight=5 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 weight=3 max_fails=3 fail_timeout=30s;
server 192.168.1.12:8080 weight=2 max_fails=3 fail_timeout=30s backup;
# 負(fù)載均衡方法
least_conn;
# 連接保持
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
server {
listen 80;
server_name health.example.com;
location / {
proxy_pass http://backend_health_check;
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 "";
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 添加健康檢查信息
add_header X-Upstream-Status $upstream_status;
add_header X-Upstream-Response-Time $upstream_response_time;
add_header X-Upstream-Addr $upstream_addr;
}
# =============================================
# 健康檢查端點(diǎn)
# =============================================
location /health {
# 限制訪問
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
# 返回健康狀態(tài)
add_header Content-Type "application/json";
return 200 '{
"status": "healthy",
"upstream": "backend_health_check",
"servers": [
{"addr": "192.168.1.10:8080", "status": "up"},
{"addr": "192.168.1.11:8080", "status": "up"},
{"addr": "192.168.1.12:8080", "status": "backup"}
]
}';
}
}
主動(dòng)健康檢查(需要nginx_plus或第三方模塊)
# =============================================
# 主動(dòng)健康檢查配置(需要nginx_plus)
# =============================================
upstream backend_active_health {
zone backend_active_health 64k;
server 192.168.1.10:8080 slow_start=30s;
server 192.168.1.11:8080 slow_start=30s;
server 192.168.1.12:8080 slow_start=30s backup;
# 主動(dòng)健康檢查
health_check interval=10s fails=3 passes=2 uri=/health port=8080;
# 負(fù)載均衡
least_conn;
# 連接保持
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
server {
listen 80;
server_name active-health.example.com;
location / {
proxy_pass http://backend_active_health;
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 "";
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 添加健康狀態(tài)信息
add_header X-Upstream-Status $upstream_status;
add_header X-Upstream-Response-Time $upstream_response_time;
add_header X-Upstream-Addr $upstream_addr;
}
# =============================================
# 健康狀態(tài)監(jiān)控
# =============================================
location /upstream_status {
# 限制訪問
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
# 顯示上游服務(wù)器狀態(tài)
upstream_status;
add_header Content-Type "text/plain";
}
}
4.2 會(huì)話保持配置
Cookie會(huì)話保持
# =============================================
# Cookie會(huì)話保持配置
# =============================================
upstream backend_sticky {
# Cookie會(huì)話保持
sticky cookie srv_id expires=1h domain=.example.com path=/ httponly secure;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
# 健康檢查
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 max_fails=3 fail_timeout=30s;
# 連接保持
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
server {
listen 80;
server_name sticky.example.com;
location / {
proxy_pass http://backend_sticky;
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 "";
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 添加會(huì)話保持信息
add_header X-LB-Session-Sticky "cookie";
add_header X-Upstream-Addr $upstream_addr;
}
# =============================================
# 會(huì)話管理
# =============================================
location /session {
# 顯示會(huì)話信息
add_header Content-Type "application/json";
return 200 '{
"session_id": "$cookie_srv_id",
"upstream_addr": "$upstream_addr",
"session_sticky": "enabled"
}';
}
}
路由會(huì)話保持
# =============================================
# 路由會(huì)話保持配置
# =============================================
upstream backend_route {
# 路由會(huì)話保持
sticky route $route_cookie $route_uri;
server 192.168.1.10:8080 route=a;
server 192.168.1.11:8080 route=b;
server 192.168.1.12:8080 route=c;
# 健康檢查
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 max_fails=3 fail_timeout=30s;
# 連接保持
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
server {
listen 80;
server_name route.example.com;
location / {
proxy_pass http://backend_route;
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 "";
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 添加路由信息
add_header X-LB-Session-Sticky "route";
add_header X-Upstream-Addr $upstream_addr;
add_header X-Route $route_cookie;
}
}
4.3 動(dòng)態(tài)負(fù)載均衡配置
基于DNS的動(dòng)態(tài)負(fù)載均衡
# =============================================
# 基于DNS的動(dòng)態(tài)負(fù)載均衡配置
# =============================================
upstream backend_dynamic {
# 啟用DNS解析
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
# 動(dòng)態(tài)服務(wù)器配置
server web1.example.com:8080 resolve;
server web2.example.com:8080 resolve;
server web3.example.com:8080 resolve;
# 健康檢查
server web1.example.com:8080 max_fails=3 fail_timeout=30s;
server web2.example.com:8080 max_fails=3 fail_timeout=30s;
server web3.example.com:8080 max_fails=3 fail_timeout=30s;
# 負(fù)載均衡方法
least_conn;
# 連接保持
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
server {
listen 80;
server_name dynamic.example.com;
location / {
proxy_pass http://backend_dynamic;
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 "";
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 添加動(dòng)態(tài)信息
add_header X-LB-Dynamic "dns_based";
add_header X-Upstream-Addr $upstream_addr;
}
}
基于服務(wù)發(fā)現(xiàn)的動(dòng)態(tài)負(fù)載均衡
# =============================================
# 基于服務(wù)發(fā)現(xiàn)的動(dòng)態(tài)負(fù)載均衡配置
# =============================================
upstream backend_service_discovery {
# 服務(wù)發(fā)現(xiàn)配置
zone backend_service_discovery 64k;
# 動(dòng)態(tài)服務(wù)器配置
server backend-service-1.example.com:8080 service=backend resolve;
server backend-service-2.example.com:8080 service=backend resolve;
server backend-service-3.example.com:8080 service=backend resolve;
# 健康檢查
health_check interval=10s fails=3 passes=2 uri=/health port=8080;
# 負(fù)載均衡方法
least_conn;
# 連接保持
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
server {
listen 80;
server_name service-discovery.example.com;
location / {
proxy_pass http://backend_service_discovery;
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 "";
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 添加服務(wù)發(fā)現(xiàn)信息
add_header X-LB-Service-Discovery "enabled";
add_header X-Upstream-Addr $upstream_addr;
}
# =============================================
# 服務(wù)發(fā)現(xiàn)狀態(tài)
# =============================================
location /service_status {
# 限制訪問
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
# 顯示服務(wù)發(fā)現(xiàn)狀態(tài)
add_header Content-Type "application/json";
return 200 '{
"service_discovery": "enabled",
"upstream": "backend_service_discovery",
"services": [
{"name": "backend-service-1", "status": "up"},
{"name": "backend-service-2", "status": "up"},
{"name": "backend-service-3", "status": "up"}
]
}';
}
}
4.4 灰度發(fā)布配置
基于權(quán)重的灰度發(fā)布
# =============================================
# 基于權(quán)重的灰度發(fā)布配置
# =============================================
upstream backend_canary {
# 灰度發(fā)布配置
# 舊版本:80%流量
# 新版本:20%流量
server 192.168.1.10:8080 weight=8; # 舊版本
server 192.168.1.20:8080 weight=2; # 新版本
# 健康檢查
server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.20:8080 max_fails=3 fail_timeout=30s;
# 連接保持
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
server {
listen 80;
server_name canary.example.com;
location / {
proxy_pass http://backend_canary;
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 "";
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 添加灰度發(fā)布信息
add_header X-Canary-Deployment "enabled";
add_header X-Upstream-Addr $upstream_addr;
add_header X-Version-Weight "8:2";
}
# =============================================
# 版本信息
# =============================================
location /version {
# 顯示版本信息
add_header Content-Type "application/json";
return 200 '{
"canary_deployment": "enabled",
"old_version": {"weight": 8, "addr": "192.168.1.10:8080"},
"new_version": {"weight": 2, "addr": "192.168.1.20:8080"}
}';
}
}
基于用戶特征的灰度發(fā)布
# =============================================
# 基于用戶特征的灰度發(fā)布配置
# =============================================
# 定義用戶特征映射
map $cookie_user_id $user_group {
default "old";
"~^user[0-9]{1,3}$" "new"; # 用戶ID為user001-user999的用戶分配到新版本
}
# 定義后端服務(wù)器組
upstream backend_user_canary {
server 192.168.1.10:8080; # 舊版本
server 192.168.1.20:8080; # 新版本
}
server {
listen 80;
server_name user-canary.example.com;
location / {
# 根據(jù)用戶組選擇后端
if ($user_group = "new") {
proxy_pass http://192.168.1.20:8080;
}
if ($user_group = "old") {
proxy_pass http://192.168.1.10:8080;
}
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 "";
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 添加用戶灰度信息
add_header X-Canary-User-Based "enabled";
add_header X-User-Group $user_group;
add_header X-Upstream-Addr $upstream_addr;
}
# =============================================
# 用戶組信息
# =============================================
location /user_group {
# 顯示用戶組信息
add_header Content-Type "application/json";
return 200 '{
"user_canary": "enabled",
"user_id": "$cookie_user_id",
"user_group": "$user_group",
"upstream_addr": "$upstream_addr"
}';
}
}
五、負(fù)載均衡監(jiān)控與故障處理
5.1 負(fù)載均衡監(jiān)控配置
狀態(tài)監(jiān)控配置
# =============================================
# 負(fù)載均衡監(jiān)控配置
# =============================================
http {
# =============================================
# 監(jiān)控日志格式
# =============================================
# 負(fù)載均衡監(jiān)控日志格式
log_format lb_monitor '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'upstream_addr="$upstream_addr" '
'upstream_status="$upstream_status" '
'upstream_response_time="$upstream_response_time" '
'upstream_connect_time="$upstream_connect_time" '
'upstream_header_time="$upstream_header_time"';
# =============================================
# 監(jiān)控服務(wù)器配置
# =============================================
server {
listen 80;
server_name monitor.example.com;
# 負(fù)載均衡狀態(tài)頁(yè)面
location /lb_status {
# 限制訪問
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
# 顯示負(fù)載均衡狀態(tài)
stub_status on;
add_header Content-Type "text/plain";
}
# 上游服務(wù)器狀態(tài)
location /upstream_status {
# 限制訪問
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
# 顯示上游服務(wù)器狀態(tài)
upstream_status;
add_header Content-Type "text/plain";
}
# 實(shí)時(shí)監(jiān)控?cái)?shù)據(jù)
location /real_time_stats {
# 限制訪問
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
# 實(shí)時(shí)統(tǒng)計(jì)信息
add_header Content-Type "application/json";
return 200 '{
"timestamp": "$time_iso8601",
"connections": {
"active": $connections_active,
"reading": $connections_reading,
"writing": $connections_writing,
"waiting": $connections_waiting
},
"requests": {
"total": $request_counter,
"current": $connections_active
}
}';
}
# 歷史統(tǒng)計(jì)數(shù)據(jù)
location /historical_stats {
# 限制訪問
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
# 顯示歷史統(tǒng)計(jì)信息
add_header Content-Type "application/json";
return 200 '{
"historical_data": "available_in_log_files",
"log_file": "/var/log/nginx/lb_monitor.log",
"retention_days": 30
}';
}
}
}
監(jiān)控腳本配置
# =============================================
# 負(fù)載均衡監(jiān)控腳本
# 創(chuàng)建 /usr/local/nginx/scripts/lb_monitor.sh
# =============================================
#!/bin/bash
# Nginx負(fù)載均衡監(jiān)控腳本
# 用法:./lb_monitor.sh
# 配置參數(shù)
NGINX_STATUS_URL="http://localhost/lb_status"
UPSTREAM_STATUS_URL="http://localhost/upstream_status"
LOG_FILE="/var/log/nginx/lb_monitor.log"
ALERT_EMAIL="admin@example.com"
ALERT_THRESHOLD=1000
# 獲取Nginx狀態(tài)
get_nginx_status() {
curl -s $NGINX_STATUS_URL
}
# 獲取上游服務(wù)器狀態(tài)
get_upstream_status() {
curl -s $UPSTREAM_STATUS_URL
}
# 解析Nginx狀態(tài)
parse_nginx_status() {
local status=$(get_nginx_status)
local active_connections=$(echo "$status" | grep "Active connections" | awk '{print $3}')
local accepts=$(echo "$status" | awk 'NR==3 {print $1}')
local handled=$(echo "$status" | awk 'NR==3 {print $2}')
local requests=$(echo "$status" | awk 'NR==3 {print $3}')
local reading=$(echo "$status" | awk 'NR==4 {print $2}')
local writing=$(echo "$status" | awk 'NR==4 {print $4}')
local waiting=$(echo "$status" | awk 'NR==4 {print $6}')
echo "Active connections: $active_connections"
echo "Accepts: $accepts"
echo "Handled: $handled"
echo "Requests: $requests"
echo "Reading: $reading"
echo "Writing: $writing"
echo "Waiting: $waiting"
# 檢查是否超過閾值
if [ "$active_connections" -gt "$ALERT_THRESHOLD" ]; then
echo "WARNING: Active connections exceed threshold: $active_connections > $ALERT_THRESHOLD"
send_alert "High active connections detected: $active_connections"
fi
}
# 解析上游服務(wù)器狀態(tài)
parse_upstream_status() {
local status=$(get_upstream_status)
echo "Upstream Server Status:"
echo "$status"
# 檢查是否有服務(wù)器宕機(jī)
if echo "$status" | grep -q "down"; then
echo "WARNING: Some upstream servers are down"
send_alert "Upstream server down detected"
fi
}
# 發(fā)送告警
send_alert() {
local message=$1
echo "[$(date)] ALERT: $message" >> $LOG_FILE
echo "$message" | mail -s "Nginx Load Balancer Alert" $ALERT_EMAIL
}
# 記錄監(jiān)控?cái)?shù)據(jù)
log_monitor_data() {
local timestamp=$(date "+%Y-%m-%d %H:%M:%S")
local status=$(get_nginx_status)
local active_connections=$(echo "$status" | grep "Active connections" | awk '{print $3}')
local upstream_status=$(get_upstream_status)
echo "$timestamp, $active_connections, $upstream_status" >> $LOG_FILE
}
# 主函數(shù)
main() {
echo "=== Nginx Load Balancer Monitor ==="
echo "Timestamp: $(date)"
echo ""
echo "Nginx Status:"
parse_nginx_status
echo ""
echo "Upstream Status:"
parse_upstream_status
echo ""
echo "Logging monitor data..."
log_monitor_data
echo "Monitoring completed."
}
# 執(zhí)行主函數(shù)
main
5.2 故障處理配置
故障轉(zhuǎn)移配置
# =============================================
# 故障轉(zhuǎn)移配置
# =============================================
upstream backend_failover {
# 主服務(wù)器
server 192.168.1.10:8080 weight=5 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 weight=3 max_fails=3 fail_timeout=30s;
# 備份服務(wù)器
server 192.168.1.20:8080 backup;
server 192.168.1.21:8080 backup;
# 負(fù)載均衡方法
least_conn;
# 連接保持
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
server {
listen 80;
server_name failover.example.com;
location / {
proxy_pass http://backend_failover;
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 "";
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 故障轉(zhuǎn)移配置
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_next_upstream_tries 3;
proxy_next_upstream_timeout 10s;
# 添加故障轉(zhuǎn)移信息
add_header X-Failover "enabled";
add_header X-Upstream-Addr $upstream_addr;
add_header X-Upstream-Status $upstream_status;
}
# =============================================
# 故障狀態(tài)頁(yè)面
# =============================================
location /failover_status {
# 限制訪問
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
# 顯示故障轉(zhuǎn)移狀態(tài)
add_header Content-Type "application/json";
return 200 '{
"failover": "enabled",
"primary_servers": [
{"addr": "192.168.1.10:8080", "status": "up"},
{"addr": "192.168.1.11:8080", "status": "up"}
],
"backup_servers": [
{"addr": "192.168.1.20:8080", "status": "standby"},
{"addr": "192.168.1.21:8080", "status": "standby"}
]
}';
}
}
熔斷器配置
# =============================================
# 熔斷器配置
# =============================================
# 定義熔斷器狀態(tài)變量
map $upstream_addr $circuit_breaker_status {
default "closed";
192.168.1.10:8080 "closed";
192.168.1.11:8080 "closed";
192.168.1.12:8080 "closed";
}
upstream backend_circuit_breaker {
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 max_fails=3 fail_timeout=30s;
# 負(fù)載均衡方法
least_conn;
# 連接保持
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
server {
listen 80;
server_name circuit-breaker.example.com;
location / {
# 熔斷器檢查
if ($circuit_breaker_status = "open") {
return 503 "Service Unavailable - Circuit Breaker Open";
}
proxy_pass http://backend_circuit_breaker;
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 "";
proxy_connect_timeout 5s;
proxy_send_timeout 5s;
proxy_read_timeout 5s;
# 熔斷器配置
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_next_upstream_tries 2;
proxy_next_upstream_timeout 5s;
# 添加熔斷器信息
add_header X-Circuit-Breaker $circuit_breaker_status;
add_header X-Upstream-Addr $upstream_addr;
add_header X-Upstream-Status $upstream_status;
}
# =============================================
# 熔斷器狀態(tài)管理
# =============================================
location /circuit_breaker {
# 限制訪問
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
# 熔斷器控制
if ($args ~* "action=open") {
return 200 'Circuit breaker opened manually';
}
if ($args ~* "action=close") {
return 200 'Circuit breaker closed manually';
}
# 顯示熔斷器狀態(tài)
add_header Content-Type "application/json";
return 200 '{
"circuit_breaker": "enabled",
"status": "$circuit_breaker_status",
"upstream_addr": "$upstream_addr",
"upstream_status": "$upstream_status"
}';
}
}
六、實(shí)戰(zhàn)案例
6.1 電商網(wǎng)站負(fù)載均衡配置
電商網(wǎng)站負(fù)載均衡架構(gòu)
# =============================================
# 電商網(wǎng)站負(fù)載均衡配置
# =============================================
# 用戶服務(wù)負(fù)載均衡
upstream user_service {
least_conn;
server 192.168.1.10:8080 weight=3 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 weight=3 max_fails=3 fail_timeout=30s;
server 192.168.1.12:8080 weight=2 max_fails=3 fail_timeout=30s backup;
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
# 商品服務(wù)負(fù)載均衡
upstream product_service {
ip_hash;
server 192.168.1.20:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.21:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.22:8080 max_fails=3 fail_timeout=30s backup;
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
# 訂單服務(wù)負(fù)載均衡
upstream order_service {
least_conn;
server 192.168.1.30:8080 weight=4 max_fails=3 fail_timeout=30s;
server 192.168.1.31:8080 weight=4 max_fails=3 fail_timeout=30s;
server 192.168.1.32:8080 weight=2 max_fails=3 fail_timeout=30s backup;
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
# 支付服務(wù)負(fù)載均衡
upstream payment_service {
least_conn;
server 192.168.1.40:8080 weight=5 max_fails=2 fail_timeout=15s;
server 192.168.1.41:8080 weight=5 max_fails=2 fail_timeout=15s;
server 192.168.1.42:8080 backup;
keepalive 16;
keepalive_timeout 30s;
keepalive_requests 500;
}
server {
listen 80;
server_name ecommerce.example.com;
access_log /var/log/nginx/ecommerce.example.com.access.log main;
error_log /var/log/nginx/ecommerce.example.com.error.log warn;
# =============================================
# 靜態(tài)資源
# =============================================
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|eot|svg)$ {
root /usr/local/nginx/html/ecommerce;
expires 7d;
add_header Cache-Control "public, no-transform";
access_log off;
}
# =============================================
# 用戶服務(wù)
# =============================================
location /api/user/ {
proxy_pass http://user_service;
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 "";
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
# 用戶服務(wù)會(huì)話保持
proxy_cookie_path / /;
proxy_cookie_domain off;
# 添加服務(wù)標(biāo)識(shí)
add_header X-Service "user_service";
add_header X-Upstream-Addr $upstream_addr;
}
# =============================================
# 商品服務(wù)
# =============================================
location /api/product/ {
proxy_pass http://product_service;
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 "";
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
# 商品服務(wù)緩存
proxy_cache product_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_key $scheme$request_method$host$request_uri;
# 添加服務(wù)標(biāo)識(shí)
add_header X-Service "product_service";
add_header X-Upstream-Addr $upstream_addr;
add_header X-Cache-Status $upstream_cache_status;
}
# =============================================
# 訂單服務(wù)
# =============================================
location /api/order/ {
proxy_pass http://order_service;
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 "";
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 訂單服務(wù)重試機(jī)制
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_next_upstream_tries 3;
# 添加服務(wù)標(biāo)識(shí)
add_header X-Service "order_service";
add_header X-Upstream-Addr $upstream_addr;
}
# =============================================
# 支付服務(wù)
# =============================================
location /api/payment/ {
proxy_pass http://payment_service;
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 "";
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
# 支付服務(wù)嚴(yán)格超時(shí)
proxy_next_upstream error timeout;
proxy_next_upstream_tries 2;
# 添加服務(wù)標(biāo)識(shí)
add_header X-Service "payment_service";
add_header X-Upstream-Addr $upstream_addr;
}
# =============================================
# 健康檢查
# =============================================
location /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
# =============================================
# 服務(wù)狀態(tài)
# =============================================
location /service_status {
# 限制訪問
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
# 顯示服務(wù)狀態(tài)
add_header Content-Type "application/json";
return 200 '{
"services": {
"user_service": {"status": "active", "algorithm": "least_conn"},
"product_service": {"status": "active", "algorithm": "ip_hash"},
"order_service": {"status": "active", "algorithm": "least_conn"},
"payment_service": {"status": "active", "algorithm": "least_conn"}
}
}';
}
}
6.2 微服務(wù)架構(gòu)負(fù)載均衡配置
微服務(wù)負(fù)載均衡架構(gòu)
# =============================================
# 微服務(wù)架構(gòu)負(fù)載均衡配置
# =============================================
# API網(wǎng)關(guān)負(fù)載均衡
upstream api_gateway {
least_conn;
server 192.168.1.10:8080 weight=3 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 weight=3 max_fails=3 fail_timeout=30s;
server 192.168.1.12:8080 weight=2 max_fails=3 fail_timeout=30s backup;
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
# 認(rèn)證服務(wù)負(fù)載均衡
upstream auth_service {
least_conn;
server 192.168.1.20:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.21:8080 max_fails=3 fail_timeout=30s;
keepalive 16;
keepalive_timeout 30s;
keepalive_requests 500;
}
# 用戶服務(wù)負(fù)載均衡
upstream user_service {
ip_hash;
server 192.168.1.30:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.31:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.32:8080 max_fails=3 fail_timeout=30s backup;
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
# 業(yè)務(wù)服務(wù)負(fù)載均衡
upstream business_service {
least_conn;
server 192.168.1.40:8080 weight=2 max_fails=3 fail_timeout=30s;
server 192.168.1.41:8080 weight=2 max_fails=3 fail_timeout=30s;
server 192.168.1.42:8080 weight=1 max_fails=3 fail_timeout=30s;
server 192.168.1.43:8080 weight=1 max_fails=3 fail_timeout=30s backup;
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
# 消息服務(wù)負(fù)載均衡
upstream message_service {
least_conn;
server 192.168.1.50:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.51:8080 max_fails=3 fail_timeout=30s;
keepalive 16;
keepalive_timeout 30s;
keepalive_requests 500;
}
# 文件服務(wù)負(fù)載均衡
upstream file_service {
least_conn;
server 192.168.1.60:8080 weight=3 max_fails=3 fail_timeout=30s;
server 192.168.1.61:8080 weight=3 max_fails=3 fail_timeout=30s;
server 192.168.1.62:8080 weight=2 max_fails=3 fail_timeout=30s backup;
keepalive 32;
keepalive_timeout 30s;
keepalive_requests 1000;
}
server {
listen 80;
server_name microservice.example.com;
access_log /var/log/nginx/microservice.example.com.access.log main;
error_log /var/log/nginx/microservice.example.com.error.log warn;
# =============================================
# API網(wǎng)關(guān)
# =============================================
location / {
proxy_pass http://api_gateway;
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 "";
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
# API網(wǎng)關(guān)重試機(jī)制
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_next_upstream_tries 3;
# 添加網(wǎng)關(guān)標(biāo)識(shí)
add_header X-Gateway "nginx";
add_header X-Upstream-Addr $upstream_addr;
}
# =============================================
# 內(nèi)部服務(wù)路由
# =============================================
# 認(rèn)證服務(wù)
location /internal/auth/ {
proxy_pass http://auth_service;
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 "";
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
# 認(rèn)證服務(wù)緩存
proxy_cache auth_cache;
proxy_cache_valid 200 302 5m;
proxy_cache_valid 404 1m;
proxy_cache_key $scheme$request_method$host$request_uri;
add_header X-Service "auth_service";
add_header X-Upstream-Addr $upstream_addr;
add_header X-Cache-Status $upstream_cache_status;
}
# 用戶服務(wù)
location /internal/user/ {
proxy_pass http://user_service;
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 "";
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
add_header X-Service "user_service";
add_header X-Upstream-Addr $upstream_addr;
}
# 業(yè)務(wù)服務(wù)
location /internal/business/ {
proxy_pass http://business_service;
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 "";
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
# 業(yè)務(wù)服務(wù)重試機(jī)制
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_next_upstream_tries 3;
add_header X-Service "business_service";
add_header X-Upstream-Addr $upstream_addr;
}
# 消息服務(wù)
location /internal/message/ {
proxy_pass http://message_service;
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 "";
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
add_header X-Service "message_service";
add_header X-Upstream-Addr $upstream_addr;
}
# 文件服務(wù)
location /internal/file/ {
proxy_pass http://file_service;
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 "";
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 文件服務(wù)大文件支持
client_max_body_size 100m;
proxy_max_temp_file_size 1024m;
add_header X-Service "file_service";
add_header X-Upstream-Addr $upstream_addr;
}
# =============================================
# 服務(wù)發(fā)現(xiàn)和健康檢查
# =============================================
location /service_discovery {
# 限制訪問
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
# 顯示服務(wù)發(fā)現(xiàn)狀態(tài)
add_header Content-Type "application/json";
return 200 '{
"microservices": {
"api_gateway": {"status": "active", "servers": 3},
"auth_service": {"status": "active", "servers": 2},
"user_service": {"status": "active", "servers": 3},
"business_service": {"status": "active", "servers": 4},
"message_service": {"status": "active", "servers": 2},
"file_service": {"status": "active", "servers": 3}
}
}';
}
# =============================================
# 健康檢查
# =============================================
location /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
}
性能優(yōu)化建議:
- 合理配置連接保持參數(shù)
- 啟用緩存提高響應(yīng)速度
- 根據(jù)服務(wù)器性能配置權(quán)重
- 實(shí)現(xiàn)動(dòng)態(tài)擴(kuò)容和縮容
- 定期監(jiān)控和優(yōu)化負(fù)載均衡效果
高可用性建議:
- 配置備份服務(wù)器
- 實(shí)現(xiàn)故障自動(dòng)轉(zhuǎn)移
- 建立熔斷機(jī)制防止雪崩
- 實(shí)現(xiàn)灰度發(fā)布降低風(fēng)險(xiǎn)
- 定期演練故障恢復(fù)流程
Nginx負(fù)載均衡是構(gòu)建高可用、高性能系統(tǒng)的關(guān)鍵技術(shù)。通過本文的學(xué)習(xí),你應(yīng)該能夠根據(jù)實(shí)際業(yè)務(wù)需求,設(shè)計(jì)并實(shí)現(xiàn)合適的負(fù)載均衡方案,為系統(tǒng)的穩(wěn)定運(yùn)行提供有力保障。
以上就是Nginx中多種負(fù)載均衡策略配置的實(shí)戰(zhàn)指南的詳細(xì)內(nèi)容,更多關(guān)于Nginx負(fù)載均衡的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- Nginx負(fù)載均衡通用方案詳解
- Nginx負(fù)載均衡與健康檢查使用詳解
- 詳解Nginx中常見負(fù)載均衡策略配置與使用場(chǎng)景
- Nginx 負(fù)載均衡和緩存配置最佳實(shí)踐
- 通過nginx做mysql的負(fù)載均衡實(shí)現(xiàn)過程
- Nginx+Tomcat負(fù)載均衡群集全過程
- Nginx部署負(fù)載均衡服務(wù)的步驟全解析
- nginx負(fù)載均衡配置方式
- nginx負(fù)載均衡及詳細(xì)配置方法
- nginx實(shí)現(xiàn)負(fù)載均衡與實(shí)例解讀
- Nginx幾種負(fù)載均衡模式的實(shí)現(xiàn)示例
相關(guān)文章
Nginx+Tomcat反向代理與負(fù)載均衡的實(shí)現(xiàn)
這篇文章給大家詳細(xì)介紹了如何實(shí)現(xiàn)Nginx+Tomcat反向代理與負(fù)載均衡,文中的流程步驟介紹的非常詳細(xì)對(duì)我們的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2023-07-07
nginx+tomcat 通過域名訪問項(xiàng)目的實(shí)例
這篇文章主要介紹了nginx+tomcat 通過域名訪問項(xiàng)目的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05
Nginx幾種負(fù)載均衡模式的實(shí)現(xiàn)示例
本文主要介紹了Nginx幾種負(fù)載均衡模式的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-10-10
Nginx配置并兼容HTTP實(shí)現(xiàn)代碼解析
這篇文章主要介紹了Nginx配置并兼容HTTP實(shí)現(xiàn)代碼解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11
nginx如何實(shí)現(xiàn)配置靜態(tài)資源服務(wù)器及防盜鏈
這篇文章主要為大家介紹了nginx實(shí)現(xiàn)配置靜態(tài)資源服務(wù)器及防盜鏈步驟詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11

