解决 Kubernetes Ingress 访问报错 503 Service Temporarily Unavailable
分析 Kubernetes Ingress 报 503 诱因,详解 Service selector 标签脱节、Endpoints 为空与就绪探针失败排查。
问题现象
通过 Kubernetes Ingress 域名访问微服务时,浏览器或客户端返回:
<html>
<head><title>503 Service Temporarily Unavailable</title></head>
<body>
<center><h1>503 Service Temporarily Unavailable</h1></center>
<hr><center>nginx</center>
</body>
</html>
在 Ingress Controller 日志中记录:
[error] 1234#0: *5678 no live upstreams while connecting to upstream, client: 10.244.1.1, request: "GET /api HTTP/1.1", upstream: "http://default-my-service-8080"
触发根因
在 Kubernetes 中,Ingress Controller(如 ingress-nginx)并不直接将流量打到 Service 的虚拟 ClusterIP,而是直接通过 CoreDNS 与 API Server 发现该 Service 关联的后方 Pod 真实容器 IP(Endpoints):
- Service 的 selector 标签与 Pod labels 不匹配:Service YAML 中的
spec.selector拼写错误,导致 Service 找不到任何对应的后端 Pod。 - Pod 就绪探针(Readiness Probe)失败:所有后端 Pod 虽然状态是
Running,但因为数据库连不上或健康检查接口超时,Readiness Probe 未通过,Pod 被控制器踢出 Endpoints 转发列表。 - Pod 全部崩溃处于 CrashLoopBackOff 或正在滚动更新中副本数为 0。
- Service 声明的 targetPort 端口与 Pod 真实监听端口错位。
诊断排查步骤
1. 查看 Service 关联的 Endpoints 是否为空
kubectl get endpoints my-service -n <namespace>
输出示例:
NAME ENDPOINTS AGE
my-service <none> 5m
若 ENDPOINTS 显示为 <none>,100% 确认是服务发现断裂,流量无处可发导致 503。
2. 核对 Service 的 selector 与 Pod 的 labels
# 查看 Service 的选择器
kubectl get svc my-service -n <namespace> -o jsonpath='{.spec.selector}'
# 查看实际 Pod 的标签
kubectl get pods -n <namespace> --show-labels
3. 检查 Pod 的就绪状态
kubectl get pods -n <namespace>
观察 READY 列:若显示 0/1,说明探针未通过。
解决方案
方案一:校准 Service 的 spec.selector 标签
修正 Service YAML,使其标签选择器与 Pod 模板中的 metadata.labels 一字不差:
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
selector:
app: my-app # 必须与 Deployment spec.template.metadata.labels.app 完全一致
ports:
- protocol: TCP
port: 80
targetPort: 8080 # 必须与容器内部真实监听端口一致
方案二:排查并修复 Pod 就绪探针(Readiness Probe)
如果 Pod 未通过就绪探针: 查看详细事件日志:
kubectl describe pod <pod-name> -n <namespace>
若提示 Readiness probe failed: HTTP probe failed with statuscode: 500:
修复后端健康检查接口,或适当调整探针初始延迟与超时:
readinessProbe:
httpGet:
path: /actuator/health
port: 8080
initialDelaySeconds: 30 # 给予充分冷启动缓冲
periodSeconds: 10
timeoutSeconds: 3
failureThreshold: 3
方案三:确保 Ingress 的 service.port 与 Service 端口一致
在 Ingress 配置中核对端口名称或数字:
spec:
rules:
- host: api.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: my-service
port:
number: 80 # 与 Service 的 port 对应
验证方法
修复后再次检查 Endpoints:
kubectl get endpoints my-service -n <namespace>
输出显示:
NAME ENDPOINTS AGE
my-service 10.244.1.25:8080,10.244.2.14:8080 10m
成功挂载就绪的 Pod IP。再次发起 Ingress 访问,立即返回 200 OK,503 彻底排除。


