这次记录一个 K8s 里的 502 问题。
应用 Pod 已经启动,Ingress 也配置好了,域名能访问到网关,但返回 502。
这类问题不要一上来就改 Ingress。我的排查顺序是:Pod、Service、Endpoints、readinessProbe,最后才看 Ingress。
环境
| 项目 | 内容 |
|---|---|
| 集群 | K8s 测试集群 |
| 入口 | Ingress |
| 服务 | Web 应用 |
| 现象 | Ingress 返回 502 |
第一步:确认 Pod 状态
kubectl get pods -o wide
kubectl describe pod <pod-name>
kubectl logs <pod-name> --tail=100
如果 Pod 还在 ImagePullBackOff、CrashLoopBackOff 或 Pending,先不要看 Ingress。
镜像拉不下来时,先排节点网络、镜像仓库和拉取凭据。
第二步:确认 Service 端口
查看 Service:
kubectl get svc
kubectl describe svc web
重点看:
porttargetPort- selector
常见错误是 Service selector 没匹配到 Pod,或者 targetPort 和容器监听端口不一致。
第三步:看 Endpoints
kubectl get endpoints web
如果 Endpoints 为空,Ingress 就到不了后端。
这时常见原因:
- Service selector 写错。
- Pod label 不匹配。
- readinessProbe 没通过。
- Pod 不在 Ready 状态。
继续看:
kubectl get pods --show-labels
kubectl describe pod <pod-name>
第四步:readinessProbe
很多应用启动慢,容器 Running 了,但 readinessProbe 没过。
示例:
readinessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
如果 /health 路径不存在,Pod 会一直不 Ready,Service Endpoints 可能为空。
先在 Pod 内测试:
kubectl exec -it <pod-name> -- wget -S -O- http://127.0.0.1:8080/health
第五步:再看 Ingress
确认 Pod、Service、Endpoints 都正常后,再看 Ingress:
kubectl describe ingress web
kubectl get ingress
检查:
- host 是否正确。
- path 是否匹配。
- serviceName 是否正确。
- servicePort 是否正确。
- Ingress Controller 日志是否有 upstream 错误。
排查清单
| 层级 | 命令 | 目标 |
|---|---|---|
| Pod | kubectl get pods |
是否 Running / Ready |
| 镜像 | kubectl describe pod |
是否 ImagePullBackOff |
| Service | kubectl describe svc |
selector 和 targetPort |
| Endpoints | kubectl get endpoints |
是否有后端地址 |
| Probe | kubectl describe pod |
readiness 是否通过 |
| Ingress | kubectl describe ingress |
host/path/service 是否正确 |
小结
Ingress 502 的本质是入口没有拿到健康上游。
所以不要只盯 Ingress YAML。先确认 Pod Ready,再确认 Service 选中了 Pod,再确认 Endpoints 有地址。
如果 Endpoints 是空的,Ingress 配得再漂亮也没用。