nginx upstream 支持异构服务器混合集群的关键是分组清晰、权重合理、健康可控、路由可感知;需按环境/平台语义拆分独立 upstream 组,禁用 ip_hash,结合 map+location 实现业务感知分流,并强化差异化健康检查与连接控制。

要让 Nginx 的 upstream 真正支持异构服务器混合集群(比如 IDC 物理机 + 阿里云 ECS + AWS EC2 + Kubernetes Service + Windows IIS),关键不是堆节点,而是分组清晰、权重合理、健康可控、路由可感知。配置本身不难,但逻辑必须对齐业务实际。
按环境/平台语义拆分独立 upstream 组
不同来源的后端能力差异大,混在一个 upstream 里会导致健康状态污染、连接池冲突、权重失效。必须按部署形态或网络域划分:
- 给本地 IDC 节点单独建
upstream idc_cluster,用内网 IP 直连,设weight=5 max_fails=2 fail_timeout=10s - 阿里云节点归入
upstream aliyun_cluster,走 SLB 或公网,设weight=3 max_fails=3 fail_timeout=15s - AWS 节点放入
upstream aws_cluster,跨区域链路长,设weight=2 max_fails=3 fail_timeout=20s - K8s Service 用 DNS 名(如
svc-order.prod.svc.cluster.local:80),加resolve参数确保自动更新 A 记录
选对调度算法,避免 ip_hash 误用
异构集群中客户端来源复杂(CDN、NAT、Pod IP 漂移),ip_hash 容易导致负载倾斜甚至单点打满:
- 无状态短连接服务:用默认轮询,或显式写
round_robin - 长连接或多线程慢响应服务(如文件上传、WebSocket):在 upstream 首行加
least_conn - 性能明显不均时:结合
weight,但注意least_conn下 weight 只影响初始建连,不改变连接数判断逻辑 - 禁用
ip_hash,除非你确认所有流量都来自固定出口 IP(如企业专线)
用 map + location 实现业务感知分流
单纯靠 upstream 分组还不够,得让请求“知道自己该去哪”:
- 按路径路由:
location ^~ /api/v2/sync/ { proxy_pass http://aliyun_cluster; } - 按请求头识别偏好:
map $http_x_cloud_pref $target_upstream { "aws" "aws_cluster"; "aliyun" "aliyun_cluster"; default "idc_cluster"; },再proxy_pass http://$target_upstream; - 按 cookie 保持会话:
hash $cookie_sessionid consistent;,前提是所有后端统一生成并透传该 cookie
强化健康检查与连接控制
异构节点故障特征不同,被动检查必须差异化,主动探测需额外模块支持:
- 统一启用被动检查:
max_fails=3 fail_timeout=30s是底线,各组可在此基础上微调 - 若需 HTTP 主动探活(如
/healthz),需编译nginx-upstream-check-module或用 OpenResty - 所有 upstream 建议加
keepalive 32;,对应 location 加proxy_http_version 1.1;和proxy_set_header Connection ''; - 透传真实信息:
proxy_set_header X-Real-IP $remote_addr;、X-Request-ID $request_id;,便于后端链路追踪











