> ## 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.

# Ingress 404 与 503 分别意味着什么：3 层转发里的失败点
- URL: https://zyx322.xyz/csdn-2026-10-24-c52dbc87698a/
- Published: 2026-10-24T04:00:00.000Z
- Updated: 2026-11-26T07:02:17.000Z
- Author: ZYX
- Tags: k8s

### 一、先把转发链路画出来

Ingress 不是"一个组件"，它至少跨三层：

```text
外部流量
   ↓
① Ingress Controller（Nginx / Traefik / ALB）
   ↓  按 host + path 匹配 Ingress 规则
② Service（ClusterIP）
   ↓  按 selector 找 Endpoint
③ Pod

```

**404 和 503 分别对应这条链路上不同的失败位置**，这是排查的第一分水岭。

| 状态码     | 失败位置        | 含义                            |
| ------- | ----------- | ----------------------------- |
| **404** | ① Ingress 层 | 规则**根本没匹配上**，流量没离开 Controller |
| **503** | ② Service 层 | 规则匹配上了，但**后端没有可用 Endpoint**   |
| **502** | ③ Pod 层     | 连上了 Pod 但连接失败/被提前关闭           |

**记住这个映射，排查时能省一半时间。**

### 二、404：规则没匹配上

404 说明 Ingress Controller **收到了请求，但找不到要转发给谁**。它压根没往后走。

#### 原因 1：host 不匹配

```yaml
spec:
  rules:
    - host: api.example.com      # 只认这个 host
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: api-svc
                port: {number: 8080}

```

如果你用 `curl http://<IP>/` 直接打 IP（不带 Host 头），host 是空的，不匹配任何规则 → **404**。

验证：

```bash
# 不带 Host → 404
curl -i http://<ingress-ip>/

# 带 Host → 正常
curl -i -H "Host: api.example.com" http://<ingress-ip>/

```

#### 原因 2：path 匹配规则和你想的不一样

`pathType` 有三个取值，行为差别很大：

| pathType               | 行为                            |
| ---------------------- | ----------------------------- |
| Exact                  | 完全相等才匹配                       |
| Prefix                 | 按**路径前缀**匹配（逐段，不是字符串前缀）       |
| ImplementationSpecific | 取决于 Controller 实现（Nginx 下是正则） |

**`Prefix` 是按 `/` 分段匹配的，不是字符串前缀**：

```text
path: /api      Prefix
  ✅ /api        匹配
  ✅ /api/v1     匹配
  ❌ /apiary     不匹配（不是完整的一段）

```

这一点经常导致"路径看着像前缀但就是 404"。

#### 原因 3：IngressClass 不匹配

集群里有多个 Ingress Controller 时，必须指定 class：

```yaml
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx    # 旧写法
spec:
  ingressClassName: nginx                 # 新写法（推荐）

```

**没写或者写错了，这个 Ingress 会被 Controller 忽略**，表现就是 404。

```bash
kubectl get ingressclass
kubectl get ingress <name> -o yaml | grep -i class

```

#### 原因 4：多个 Ingress 冲突 / 规则没被加载

```bash
# 看 Ingress 有没有被 Controller 认领（看 ADDRESS 字段有没有值）
kubectl get ingress -A

# 看 Controller 日志里的 reload
kubectl logs -n ingress-nginx deploy/ingress-nginx-controller | grep -i "reload\|error"

```

### 三、503：没有可用的后端

503 说明规则匹配上了，但 **Controller 找不到可用的 Pod 来转发**。

#### 第一步永远是看 Endpoint

```bash
kubectl get endpoints <service-name> -n <ns>
# 或者
kubectl get endpointslices -n <ns>

```

```text
NAME      ENDPOINTS
api-svc   <none>          ← 空的就是问题所在

```

**`ENDPOINTS` 为空 = Service 没有选中任何健康 Pod = 503。**

#### 原因 1：selector 和 Pod 标签对不上

```bash
# Service 选什么
kubectl get svc api-svc -o jsonpath='{.spec.selector}'

# Pod 实际有什么标签
kubectl get pod -l app=api --show-labels

```

最常见的就是 `app: api` 和 `app: api-server` 这种一字之差。

#### 原因 2：Pod 没有 Ready

Endpoint 只收 **Ready** 的 Pod。Pod Running 但 NotReady 不会被加入。

```bash
kubectl get pod -l app=api
# NAME    READY   STATUS    RESTARTS
# api-0   0/1     Running   0        ← Running 但 0/1，NotReady

```

原因通常是 **readinessProbe 失败**：

```bash
kubectl describe pod api-0 | grep -A 5 Readiness
# Readiness probe failed: HTTP probe failed with statuscode: 500

```

注意：**readiness 失败不会重启 Pod，只会把它从 Service 摘掉**。所以现象是"Pod 看着在跑，但访问 503"。

#### 原因 3：端口对不上

```yaml
# Service
spec:
  ports:
    - port: 80
      targetPort: 8080      # 要和应用实际监听的端口一致

```

`targetPort` 写错时，Endpoint 会有 IP 但**端口不通**。这种情况通常表现为 502 或连接超时，但部分 Controller 也会报 503。

```bash
# 确认 Pod 实际监听的端口
kubectl exec <pod> -- ss -lntp

```

#### 原因 4：全部后端被摘除（滚动发布期间）

滚动更新时旧 Pod 被终止、新 Pod 还没 Ready，会出现短暂的 503。

**解法是配置优雅停机 + preStop**，让旧 Pod 在退出前先等一会儿，等 endpoint 同步完成：

```yaml
lifecycle:
  preStop:
    exec:
      command: ["sh", "-c", "sleep 10"]    # 给 endpoint 摘除留出时间
terminationGracePeriodSeconds: 40

```

关于这个时间差的完整机制在滚动更新那篇里详细讲过。

### 四、502：连上了但连接失败

502 说明 Controller 找到了 Pod 并尝试连接，但**连接层面失败**：

- Pod 内的进程没监听那个端口；
- 应用启动时就把连接关了；
- keepalive 连接被复用但已被关闭。

排查重点是**从 Controller 到 Pod 这一段**：

```bash
# 直接打 Pod IP（绕过 Service，确认应用本身是否正常）
kubectl get pod -o wide     # 拿到 Pod IP
kubectl run -it --rm curl --image=curlimages/curl --restart=Never -- \
  curl -i http://<pod-ip>:8080/healthz

```

- Pod IP 直接访问正常 → 问题在 Service/Endpoint 层；
- Pod IP 也不通 → 问题在应用本身（端口、启动、崩溃）。

### 五、一个完整的排查流程

```bash
# 1. 看状态码，判断失败位置
#    404 → Controller 层；503 → Service/Endpoint 层；502 → Pod 连接层

# 2. 404：查规则
kubectl get ingress <name> -o yaml          # host / path / pathType / ingressClassName
curl -i -H "Host: <host>" http://<ip>/      # 带 Host 再试一次
kubectl logs -n ingress-nginx deploy/ingress-nginx-controller --tail=50

# 3. 503：查 Endpoint
kubectl get endpoints <svc>
kubectl get svc <svc> -o jsonpath='{.spec.selector}'
kubectl get pod -l <selector> --show-labels
kubectl describe pod <pod> | grep -A 5 Readiness

# 4. 502：绕过 Service 直连 Pod
curl http://<pod-ip>:<port>/healthz
kubectl exec <pod> -- ss -lntp

```

### 六、带走物

| 状态码     | 一句话定位                               | 第一个要看的命令                    |
| ------- | ----------------------------------- | --------------------------- |
| **404** | Ingress 规则没匹配上（host / path / class） | kubectl get ingress -o yaml |
| **503** | 规则匹配了但 Service 没有可用 Endpoint        | kubectl get endpoints       |
| **502** | 找到 Pod 但连接失败                        | 直连 Pod IP 验证                |
| **504** | Pod 连上了但响应超时                        | 查应用耗时                       |

一句话结论：**404 是"不知道往哪转"，503 是"知道往哪转但没人接"，502 是"有人但连不上"——状态码已经告诉你失败在第几层了，顺着那一层查就行。**