11 upstream 与轮询


 TL;DR
upstream 组在配置期怎么建起来、请求怎么从 location 一路走到后端、轮询表怎么维护、后端挂了怎么被摘掉。proxy 与 upstream 两个模块的分工也在这一章讲清楚。
难度 中等

nginx 最主要的工作是转发请求。这一章要回答的是:一次转发里,
「转发给谁」这件事到底由谁决定、在什么时刻决定
。

很多人以为 upstream 就是「一个后端地址列表」,其实它是三层东西:
一层是配置,一层是调度算法,一层是运行期的健康状态。
读源码把这三层分开,剩下的都好办。

读完之后你应该能回答:

  1. upstream {} 块在配置解析阶段变成了哪几个结构体?
  2. 一个请求从 location 走到后端 socket,中间经过哪几个函数?
  3. 轮询的「轮」是怎么算出来的?weight 和 current_weight 有什么区别?
  4. 后端挂掉之后,nginx 靠什么把它从轮询表里摘掉?摘掉多久?
  5. proxy 模块和 upstream 模块各管什么?为什么这么拆?

行号基于 /work/ai/cwork/nginx,版本 nginx 1.31.11(mainline,HEAD e76b6746c)。

11.1 三层结构:srv_conf、server、peer

11.1.1 upstream 组是怎么建起来的

upstream 是块指令,处理函数 ngx_http_upstream()
(src/http/ngx_http_upstream.c:6406)第一件事就是调 ngx_http_upstream_add(),为这个块
申请一份 srv_conf。传给它的权限位(src/http/ngx_http_upstream.c:6425)声明「这个 upstream 块允许被改写
哪些属性」—— CREATE、MODIFY、WEIGHT、MAX_CONNS、MAX_FAILS、
FAIL_TIMEOUT、DOWN、BACKUP(前缀都是 NGX_HTTP_UPSTREAM_)。需要权限位是因为
proxy_pass 直接写域名时,nginx 会隐式地造一个 upstream 组
(src/http/ngx_http_upstream.c:6905);ngx_http_upstream_add() 会先按名字找一遍
(src/http/ngx_http_upstream.c:6859),所以 upstream backend {} 与
proxy_pass http://backend/ 指的是同一份 srv_conf。

srv_conf 里那个 peer 字段(src/http/ngx_http_upstream.h:136)是整个 upstream
子系统的挂钩点,结构体 ngx_http_upstream_peer_t 定义在
src/http/ngx_http_upstream.h:94-98,三个字段各管一段:

字段 什么时候调 管什么
init_upstream 配置期收尾 搭出整个 peer 池(建链表、算总权重)
init 每个请求开始时 给这个请求装配调度器(设 peer.get / peer.free)
data — 上面两个函数各自的私有数据

hash、ip_hash、least_conn、least_time、random、sticky 六个模块,全都是靠替换
这三个字段来接管调度的。记住这张表,后面的算法都是同一套模板。

11.1.2 server 指令填的是什么

upstream 块里的每个 server 指令由 ngx_http_upstream_server()
(src/http/ngx_http_upstream.c:6523)处理,往 srv_conf 的 servers 数组里压一个
ngx_http_upstream_server_t(src/http/ngx_http_upstream.h:122),里面记着
weight、max_conns、max_fails、fail_timeout、down、backup。
默认值在 src/http/ngx_http_upstream.c:6546-6549:weight = 1、max_conns = 0、
max_fails = 1、fail_timeout = 10。

参数 默认 含义
weight 1 权重,平滑加权轮询里用
max_conns 0 0 = 不限并发连接数
max_fails 1 失败几次就临时摘掉
fail_timeout 10 摘掉后多久放回来(秒)

坑:max_fails = 1 意味着一次失败就足以让这台机器被踢出轮询表。而且它不是
「连续失败 N 次」,是「在 fail_timeout 时间窗内累计失败 N 次」—— 时间窗由
peer->checked 记录,见 §11.4。

11.1.3 收尾:把 server 列表变成 peer 链表

配置解析完,nginx 调 ngx_http_upstream_init_main_conf()
(src/http/ngx_http_upstream.c:7348),对每一个 upstream 组调它自己的
init_upstream(src/http/ngx_http_upstream.c:7364)。那里是个三目运算符
(src/http/ngx_http_upstream.c:7364-7365):peer.init_upstream 为空就退回
ngx_http_upstream_init_round_robin。没设 init_upstream 就用轮询。而
ngx_http_upstream_init_round_robin()
(src/http/ngx_http_upstream_round_robin.c:37)是默认实现,第一件事就是把自己塞进
peer.init 槽(src/http/ngx_http_upstream_round_robin.c:51),于是每个请求开始时都会
调到它,由它来设 peer.get。

它接着算出总数与总权重,建 peer 池:peers->single = (n == 1)、
peers->number = n、peers->weighted = (w != n)、peers->total_weight = w
(src/http/ngx_http_upstream_round_robin.c:156-159)。single / weighted
是性能优化:single 表示只有一台机器,走捷径不用遍历链表;
weighted 表示权重全相等,算法可以简化。然后逐个 server 填 peer
(src/http/ngx_http_upstream_round_robin.c:215),把 weight 同时写进
weight 和 effective_weight,而 current_weight 置 0
(src/http/ngx_http_upstream_round_robin.c:219-221)。effective_weight 初值
等于 weight,而 current_weight 初值是 0
—— 这两个字段是轮询的核心,§11.3 展开。
一个 server 指令可能解析出多个地址(naddrs > 1),每个地址都变成一个独立的
peer 节点,所以 peer 数量可能大于 server 数量。最后 us->peer.data = peers
(src/http/ngx_http_upstream_round_robin.c:242)把池子挂上。

三层结构到此成型:组级是 ngx_http_upstream_srv_conf_t(一个 upstream 一份,里面有
servers[] 配置数组和 peer 钩子);配置态是 ngx_http_upstream_server_t
(权重、max_fails…);运行态是 ngx_http_upstream_rr_peers_t 链表上挂的若干
ngx_http_upstream_rr_peer_t。

坑:这一整套 peer 池是配置期一次性建好的,运行期只读结构、只改计数。所以
「reload 之后轮询从头开始」—— 新 worker 拿到的是全新的 current_weight = 0、
fails = 0。这就是为什么 reload 会让流量分布抖一下。

11.2 请求怎么从 location 走到后端

11.2.1 proxy 与 upstream 的分工

这两个模块经常被混为一谈,职责边界却很清楚:

proxy 模块 upstream 模块
文件 src/http/modules/ngx_http_proxy_module.c src/http/ngx_http_upstream.c
干什么 协议翻译:把 HTTP 请求改写成后端要的格式,把后端响应改写回客户端要的格式 挑后端 + 管连接:决定连哪台、怎么连、失败了换不换
关键函数 ngx_http_proxy_create_request()(:1184)、ngx_http_proxy_process_status_line()(:1805) ngx_http_upstream_init()(:549)、ngx_http_upstream_connect()(:1579)

一句话:proxy 负责「说什么」,upstream 负责「对谁说」。同样的分工在 fastcgi、
uwsgi、grpc、scgi 里都成立 —— 它们共用 ngx_http_upstream.c 这一整套后端选择机制,
只各自实现协议翻译那一半。

11.2.2 完整调用链

客户端
  │ TCP → ngx_event_accept()      src/event/ngx_event_accept.c
  │        ngx_get_connection()  ← 从 worker 连接池取 slot
  ▼
ngx_http_process_request()         src/http/ngx_http_request.c
  │ 匹配 server / location
  ▼
ngx_http_proxy_handler()           proxy_module.c:876
  │ 装 u->create_request / u->process_header
  ▼
ngx_http_upstream_create()         ngx_http_upstream.c:516
  ▼
ngx_http_read_client_request_body() proxy_module.c:970
  │ 读完请求体后回调 ↓
ngx_http_upstream_init()           ngx_http_upstream.c:549  → init_request():593
  │ u->create_request(r)           ← 【协议翻译】:675
  │ uscf->peer.init(r, uscf)       ← 【装配调度器】:854
  ▼
ngx_http_upstream_connect()        ngx_http_upstream.c:1579
  │ ngx_event_connect_peer()       src/event/ngx_event_connect.c:21
  │   rc = pc->get(pc, pc->data)   ← 【选后端】:34
  │ socket() + connect()
  ▼
ngx_http_upstream_send_request()   ngx_http_upstream.c:2170
  ▼
ngx_http_upstream_process_header() ngx_http_upstream.c:2467
  │ u->process_header(r)           ← 【解析后端响应头】
  ▼
ngx_http_upstream_process_headers() ngx_http_upstream.c:3091
  ▼
ngx_http_upstream_process_upstream() ngx_http_upstream.c:4365
  │ ngx_event_pipe_read_upstream()  src/event/ngx_event_pipe.c:104
  ▼
ngx_http_upstream_send_response()  ngx_http_upstream.c:3289
  ▼
ngx_http_upstream_finalize_request() ngx_http_upstream.c:4785
  │ u->peer.free(...)              ← 【归还连接、记账】
  ▼
响应写回客户端

(proxy_module.c = src/http/modules/ngx_http_proxy_module.c,
ngx_http_upstream.c = src/http/ngx_http_upstream.c,下同。)

这条链上 proxy 模块只出现在两个位置:ngx_http_proxy_handler()
(src/http/modules/ngx_http_proxy_module.c:876)里装 u->create_request 与
u->process_header,以及 ngx_http_read_client_request_body()
(src/http/modules/ngx_http_proxy_module.c:970)读完请求体之后的回调;其余全是
src/http/ngx_http_upstream.c 里的通用逻辑。

三个必须记住的分工点:请求体读完后 u->create_request(r)
(src/http/ngx_http_upstream.c:675)由 proxy 模块把请求改写成后端格式;紧接着
uscf->peer.init(r, uscf)(src/http/ngx_http_upstream.c:854)装上 peer.get /
peer.free;真正选后端发生在 pc->get(pc, pc->data)
(src/event/ngx_event_connect.c:34)—— 调度算法在这里跑。

坑:create_request 在 peer.init 之前调用(src/http/ngx_http_upstream.c:675
vs :854)。顺序有讲究:先把请求改写完,装调度器时才知道要去哪个地址。调试时按这个
顺序断点,一次能看清两件事。

那个 peer.init 就是整个调度体系的入口。它的默认实现
ngx_http_upstream_init_round_robin_peer()
(src/http/ngx_http_upstream_round_robin.c:515)做三件事:分配本请求的 rr_peer_data、
分配 tried 位图、装上 peer.get 和 peer.free
(src/http/ngx_http_upstream_round_robin.c:564)。位图的分配是个巧思
(src/http/ngx_http_upstream_round_robin.c:551-554):后端不超过 8 台(64 位机器上
8 * sizeof(uintptr_t) = 64)时,位图就藏在 rrp->data 指针里,不额外分配;
超过 8 台才去 pool 里要内存。

11.3 轮询表是怎么维护的

11.3.1 平滑加权:三个 weight 的关系

peer 结构体(src/http/ngx_http_upstream_round_robin.h:47)里有三个容易混的字段:

字段 谁改 作用
weight(:55) 只在配置期设一次 用户的配置值,永远不变
effective_weight(:54) 运行期调整 「当前有效权重」—— 后端出问题时会被调低
current_weight(:53) 每次选择都动 「当前累计权重」—— 算法用它做比较

选一个后端的核心循环在 ngx_http_upstream_get_peer()
(src/http/ngx_http_upstream_round_robin.c:811),逐个 peer 走。它有四道
准入门禁:tried 位(本请求已经试过它)、peer->down(配置里写了 down)、
max_fails 门禁(失败超限且还在 fail_timeout 窗口里)、max_conns 门禁
(并发连接数到顶)。过了门禁才开始算权重:

// src/http/ngx_http_upstream_round_robin.c:883-893
        peer->current_weight += peer->effective_weight;
        total += peer->effective_weight;

        if (peer->effective_weight < peer->weight) {
            peer->effective_weight++;
        }

        if (best == NULL || peer->current_weight > best->current_weight) {
            best = peer;
            p = i;

三步:current_weight += effective_weight(累加);
total += effective_weight(记下这一轮所有候选的权重和);
effective_weight 若小于 weight 就 ++ —— 这就是「平滑」二字的来源:
一次失败降下去的权重,是每次选择慢慢涨回来的。

最后挑 current_weight 最大的那个,选完之后立刻把它减掉这一轮的总权重
(src/http/ngx_http_upstream_round_robin.c:906-910,best->current_weight -= total;)。
-= total 让被选中的 peer 的累计权重「欠债」,下一轮它就轮到不了,直到别人欠的债还清。
这就是平滑加权轮询:权重 3 : 1 的两台机器,比例是 3:1,但不是「3 个 1 个 3 个
1 个」那种生硬的循环,而是把请求尽量摊匀。紧接着 rrp->tried[n] |= m
(src/http/ngx_http_upstream_round_robin.c:922)打标记:这个请求已经用过这台了。

11.3.2 单台机器与 backup 组

peers->single 为真时,get_round_robin_peer()
(src/http/ngx_http_upstream_round_robin.c:697)走捷径:只要那台没 down、没超 max_conns
就直接用(src/http/ngx_http_upstream_round_robin.c:727)。server ... backup; 的机器会被
单独装进第二组 peer 池,主组挂在 peers->next 上;主组一个都不行时,
get_round_robin_peer() 会切到 backup 组重试
(src/http/ngx_http_upstream_round_robin.c:772),并且把位图清空
(src/http/ngx_http_upstream_round_robin.c:783-785,rrp->tried[i] = 0;)—— 也就是说
backup 组的机器可以跟主组重复:主组某台试过了,backup 那台照样能试。

11.4 后端挂了怎么被摘掉

11.4.1 失败记账:free 时才更新

关键点:nginx 不主动探测后端健康。「后端挂了」是靠请求失败时顺手记一笔发现的。记账
发生在 ngx_http_upstream_free_round_robin_peer_locked()
(src/http/ngx_http_upstream_round_robin.c:1023):

// src/http/ngx_http_upstream_round_robin.c:1056-1068
    if (state & NGX_PEER_FAILED) {
        now = ngx_time();

        peer->fails++;
        peer->accessed = now;
        peer->checked = now;

        if (peer->max_fails) {
            peer->effective_weight -= peer->weight / peer->max_fails;

            if (peer->fails >= peer->max_fails) {
                ngx_log_error(NGX_LOG_WARN, pc->log, 0,
                              "upstream server temporarily disabled");

四条动作:peer->fails++(失败计数加一);peer->checked = now(记录「最后一次确认
失败的时间」
);effective_weight -= weight / max_fails(权重降一级,默认 1 次就降
weight/1,直接归零);fails = 0(else 分支,
src/http/ngx_http_upstream_round_robin.c:1080,请求成功就把失败计数清零)。

「摘掉一台后端」其实是两件事叠加:门禁(§11.3.1 里的第三道 continue 让它不被
选中,时间到了自动恢复)加上降权(effective_weight 被扣掉)。默认 max_fails=1
时,第一次失败就把 effective_weight 扣到 0,这台机器在接下来的 10 秒里既不被选中、
权重也是 0 —— 等价于被摘掉。日志里那行 upstream server temporarily disabled
就是这时候打的。

坑:peer->fails 和 peer->checked 是分开的。checked 是「最近一次失败的
时间」,accessed 是「最近一次被访问的时间」。选择时的门禁条件是
now - peer->checked <= peer->fail_timeout —— 也就是「最近一次失败还在 10 秒内,
就继续别选它」。10 秒后 checked 变旧,门禁自动失效,这台机器就回来了。

这 10 秒是「冷却时间」,不是「健康检查间隔」。nginx 全程没有发过一个探测包。

11.4.2 换个后端重试:next_upstream

失败之后换一台重试,逻辑在 ngx_http_upstream_next()
(src/http/ngx_http_upstream.c:4613),那里按状态码决定 state 取哪个值
(src/http/ngx_http_upstream.c:4628-4635):403 / 404 不算这台机器的错(它好好地
回答了),所以只记 NGX_PEER_NEXT,不增加 fails;其他情况才记 NGX_PEER_FAILED,
触发 §11.4.1 的降权。

next_upstream 是一个位掩码,默认值在
src/http/modules/ngx_http_proxy_module.c:3849-3853,只有
NGX_HTTP_UPSTREAM_FT_ERROR 和 NGX_HTTP_UPSTREAM_FT_TIMEOUT 两位。
可选位定义在 src/http/ngx_http_upstream.h:20,除了这两个还有
NGX_HTTP_UPSTREAM_FT_INVALID_HEADER(后端返回非法响应头)、一串
NGX_HTTP_UPSTREAM_FT_HTTP_500 / 502 / 503 / 504 / 403 / 404 / 429
(对应状态码),以及两个内部位 NGX_HTTP_UPSTREAM_FT_NON_IDEMPOTENT
(请求不幂等)和 NGX_HTTP_UPSTREAM_FT_NOLIVE(没有活着的后端)。

坑:默认配置下,后端返回 502 时 nginx 不会换后端重试。要让它重试得显式写
proxy_next_upstream error timeout http_502 http_503 http_504;。这是最常见的
「反代不 failover」的原因。

另外还有一道非幂等保护,在 ngx_http_upstream_test_next()
(src/http/ngx_http_upstream.c:2805):u->request_sent 且方法属于
NGX_HTTP_POST|NGX_HTTP_LOCK|NGX_HTTP_PATCH 时,掩码里会被加上
NGX_HTTP_UPSTREAM_FT_NON_IDEMPOTENT(src/http/ngx_http_upstream.c:2821-2827)。
请求已经发出去、而且方法不是幂等的,就不重试 —— 重发一次可能等于下单两次。

11.5 一台慢后端为什么能拖垮整个 nginx

nginx 没有主动健康检查。开源版里 health_check 指令不存在 ——
grep -rn "health_check" src/ 只匹配到两个结构体里的位域定义
(src/http/ngx_http_request.h:580、src/stream/ngx_stream.h:296),真正的 health_check
指令是 nginx Plus 的功能。于是开源版里,一台「变慢但没断」的后端会这样拖垮全局:

  1. 它的请求开始超时,而不是失败。超时走 NGX_HTTP_UPSTREAM_FT_TIMEOUT,
    默认在 next_upstream 里 —— 会换后端重试。但这一次请求仍然占着连接不放,
    直到 proxy_read_timeout 超时(默认 60 秒,
    src/http/modules/ngx_http_proxy_module.c:3737-3738)。而重试会成倍放大
    请求量:1 个客户端请求 → N 台后端各试一次 → 后端收到的流量是 N 倍。
    越慢的后端,越是被重试得多。
  2. 连接是从同一个池子里取的。客户端连接和到后端的连接共用
    ngx_cycle->free_connections,ngx_get_connection()
    (src/core/ngx_connection.c:1207)是唯一的入口。池子空了就是那条
    worker_connections are not enough 的错误日志(src/core/ngx_connection.c:1227)。
    worker_connections 默认 512(src/event/ngx_event.c:13,
    #define DEFAULT_CONNECTIONS 512)。

于是链条是:后端变慢 → 请求挂住 60 秒 → 连接池被占满 → 新连接全部被拒。
慢的那一台,拖垮的是整个 worker。

坑:这是反代最经典的故障模式,而且日志上看不出来。后端日志里只有零星几个
请求,nginx 日志里 worker_connections are not enough 一片 —— 原因是慢请求堆积在
nginx 这一侧
,后端根本没收到。

缓解手段:调小 proxy_read_timeout、调小 proxy_next_upstream_tries
(src/http/ngx_http_upstream.c:862 那个判断就是用它裁剪 peer.tries),
或者上 keepalive 连接池(下一章)。

11.6 小结

  • upstream 组是三层:srv_conf(组)→ server_t(配置)→ peer_t(运行期);
    配置期建好,运行期只改计数。
  • 三个挂钩点 init_upstream / init / data(src/http/ngx_http_upstream.h:94-98)是所有
    调度算法的统一入口 —— hash、ip_hash、least_conn、least_time、random、sticky 全靠替换它们。
  • 请求路径上分工明确:u->create_request 做协议翻译(proxy 模块),uscf->peer.init
    装配调度器,pc->get 真正选后端。
  • 轮询靠三个 weight:weight 恒定、effective_weight 可降可涨、
    current_weight 每次比较。降权慢慢恢复,所以叫「平滑」。
  • 健康检查是被动的:失败时记账,选择时按 max_fails + fail_timeout 门禁过滤,
    没有探测包。
  • next_upstream 默认只有 error + timeout,不含 502/503;非幂等请求(POST)发出去后不重试。

下一篇讲 连接池与调度算法:keepalive 连接池怎么管、空闲连接什么时候被回收、
五种调度算法各按什么挑后端。

参考

  • 源码树:/work/ai/cwork/nginx(nginx 1.31.11,mainline,HEAD e76b6746c)
  • 核心文件:src/http/ngx_http_upstream.c(upstream 主体)、
    src/http/ngx_http_upstream.h(ngx_http_upstream_peer_t 等结构体)、
    src/http/ngx_http_upstream_round_robin.c(默认轮询实现)、
    src/http/ngx_http_upstream_round_robin.h(rr_peer_t / rr_peers_t)、
    src/http/modules/ngx_http_proxy_module.c(proxy 协议翻译)
  • 官方文档:
    Upstream module、
    Proxy module

文章作者: growdu
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 growdu !
  目录