> ## Content Index
> Fetch the complete content index at: https://zyx322.xyz/llms.txt
> Use this file to discover other available public pages before exploring further.

# Nginx 502 与 504 的区别：一次请求在两个超时点上的失败
- URL: https://zyx322.xyz/csdn-2026-10-13-8ab771a63bd6/
- Published: 2026-10-13T04:00:00.000Z
- Updated: 2026-11-26T07:02:14.000Z
- Author: ZYX
- Tags: 网络与运维

### 一、一个请求在 Nginx 上会经过两个超时

Nginx 作为反向代理时，一次请求要跨**两条 TCP 连接**：

```text
client ────①────> Nginx ────②────> upstream(应用)

```

对应两组超时：

| 连接                 | 超时参数                                                                  | 超时后返回         |
| ------------------ | --------------------------------------------------------------------- | ------------- |
| ① 客户端 → Nginx      | client\_header\_timeout / client\_body\_timeout                       | 408 / 499     |
| ② Nginx → upstream | proxy\_connect\_timeout / proxy\_read\_timeout / proxy\_send\_timeout | **502 或 504** |

**502 和 504 的差异，就出在第 ② 条连接的不同阶段：**

- **连不上**（TCP 握手失败、连接被拒、upstream 不存在）→ **502**
- **连上了，但等不到响应**（upstream 处理太慢）→ **504**

这个区分非常重要，因为两者的排查方向完全不同。

### 二、502 Bad Gateway：连接层面的失败

#### 触发条件

Nginx 在以下情况返回 502：

1. `proxy_connect_timeout`（默认 **60s**）内没能和 upstream 建立 TCP 连接；
2. upstream 直接拒绝了连接（端口没监听）；
3. upstream 在发送响应头之前就把连接关了；
4. DNS 解析不出 upstream 域名；
5. upstream 的 keepalive 连接已经被对端关掉，Nginx 复用了一条死连接。

#### 日志里长什么样

```text
2026/10/13 00:12:03 [error] 12345#0: *6789 connect() failed (111: Connection refused)
while connecting to upstream, client: 10.0.0.5, server: api.example.com,
request: "POST /order HTTP/1.1", upstream: "http://10.0.1.20:8080/order"

```

关键字段：`connect() failed (111: Connection refused) while connecting to upstream`。

其他常见变体：

```text
# 连不上（超时）
connect() failed (110: Connection timed out) while connecting to upstream

# 没有可用上游
no live upstreams while connecting to upstream

# 上游提前关闭连接
upstream prematurely closed connection while reading response header from upstream

# 域名解析失败
no resolver defined to resolve xxx

```

#### 排查顺序

```bash
# 1. upstream 还活着吗
ss -lntp | grep 8080

# 2. 从 Nginx 这台机器上能连上吗（关键：要在 Nginx 本机测）
curl -v -m 3 http://10.0.1.20:8080/healthz

# 3. DNS 能解析吗（如果 upstream 写的是域名）
nslookup upstream.internal

# 4. 看 Nginx 的错误日志
tail -100 /var/log/nginx/error.log | grep -i "upstream"

```

#### 一个高频坑：keepalive 连接被复用

这个坑很值钱。如果 upstream（比如某个应用）有 **keepalive 超时**（Tomcat 默认 20s、Go 的默认更长），它会在空闲一段时间后主动发 FIN 关闭连接。而 Nginx 的 upstream keepalive 连接池**不一定立刻感知到**，等到下一个请求复用这条已经半关闭的连接时，就会报 502。

解决办法是给 upstream 配 keepalive 并合理设置：

```nginx
upstream backend {
    server 10.0.1.20:8080;
    keepalive 64;              # 每个 worker 维护的连接池大小
}

server {
    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;              # keepalive 需要 HTTP/1.1
        proxy_set_header Connection "";      # 清空 Connection 头，不要传 close
        proxy_connect_timeout 5s;            # 连接超时不要设太长，快速失败
        proxy_read_timeout 30s;
    }
}

```

**`proxy_http_version 1.1` 和 `proxy_set_header Connection ""` 这两行缺一不可**，否则 keepalive 不生效，Nginx 会每条请求新建连接。

### 三、504 Gateway Timeout：等待响应超时

#### 触发条件

TCP 连接建立成功了，但 upstream 在 `proxy_read_timeout`（默认 **60s**）内**没有返回任何数据**。

注意是"没返回任何数据"，不是"没返回完整响应"——upstream 只要持续在发数据，就不会触发。

#### 日志

```text
2026/10/13 00:15:41 [error] 12345#0: *6790 upstream timed out
(110: Connection timed out) while reading response header from upstream,
client: 10.0.0.5, server: api.example.com,
request: "GET /report HTTP/1.1", upstream: "http://10.0.1.20:8080/report"

```

关键字段：`upstream timed out while reading response header from upstream`。

#### 排查方向

502 查的是"能不能连上"，504 查的是"为什么慢"：

```bash
# 1. 直接打 upstream，量一下真实耗时
curl -w "dns=%{time_namelookup} tcp=%{time_connect} ttfb=%{time_starttransfer} total=%{time_total}\n" \
     -o /dev/null -s http://10.0.1.20:8080/report

# 2. 上游慢在哪：看应用的慢查询 / 慢日志 / pprof

```

`ttfb`（首字节时间）如果就超过 60s，那 Nginx 报 504 是正确的——**问题在上游，不在 Nginx**。

#### 504 时不要盲目调大超时

很多人第一反应是把 `proxy_read_timeout` 从 60s 调到 300s。这通常是个坏主意：

- 请求会在 Nginx 上挂住 5 分钟，占住一个 worker 连接；
- 客户端（或更上游的网关）大概率早就超时断开了，这个请求变成了纯粹的浪费；
- 上游慢的根因没解决，只是把 504 变成"很慢的成功"。

**正确顺序**：先量出上游真实耗时 → 优化上游（加索引、加缓存、异步化） → 最后再考虑调整超时值，并且**超时应逐级收敛**（下游 < 上游 < 网关 < 客户端）。

### 四、一张对照表

|       | 502 Bad Gateway                               | 504 Gateway Timeout                              |
| ----- | --------------------------------------------- | ------------------------------------------------ |
| 失败阶段  | 建立连接 / 连接被拒                                   | 已连接但等不到响应                                        |
| 相关参数  | proxy\_connect\_timeout                       | proxy\_read\_timeout / proxy\_send\_timeout      |
| 日志关键词 | connect() failed while connecting to upstream | upstream timed out while reading response header |
| 常见原因  | 应用没启动、端口不通、DNS 失败、keepalive 死连接               | 应用慢（慢 SQL、下游依赖慢、死循环）                             |
| 排查动作  | 从 Nginx 本机 curl upstream                      | 直接打 upstream 量 ttfb                              |
| 误治    | 调大 connect 超时                                 | 调大 read 超时（应先优化上游）                               |

还有两个容易混淆的状态码，一并记住：

- **499**：**客户端**在 Nginx 返回之前就断开了。这通常是**更上游的网关超时比 Nginx 短**导致的——不是 Nginx 的问题，是超时链路上层设短了。
- **503**：upstream 被 `max_fails` 标记为不可用，或者所有节点都被摘掉了。查 `nginx.conf` 里的 `max_fails` / `fail_timeout`。

### 五、带走物

排查流程：

```text
1. 看 Nginx error.log 的关键词
   ├─ "connect() failed ... while connecting to upstream" → 502，查连通性
   ├─ "upstream timed out ... reading response header"    → 504，查上游耗时
   ├─ "no live upstreams"                                 → 503，查 max_fails
   └─ access log 里是 499                                  → 客户端/上层网关先断了

2. 502：在 Nginx 本机执行
   ss -lntp | grep <port>          # 端口在不在
   curl -v -m 3 http://<upstream>  # 能不能连

3. 504：直接打上游，量 ttfb
   curl -w "ttfb=%{time_starttransfer}\n" ...

4. 顺手检查 upstream 是否配了 keepalive
   缺 proxy_http_version 1.1 + Connection "" → 每次新建连接，502 概率上升

```

一句话结论：**502 是"连不上"，504 是"连上了但等不到"；前者查连通性，后者查耗时——两者不要混着排查。**