Kubernetes Service 访问报 Connection refused 且 Endpoints 为空排查
分析 Kubernetes Service 无法转发请求且 Endpoints 列表为空的标签失配与端口配置错误根因。
故障现象
在 Kubernetes 集群内部,客户端 Pod 通过 Service 名称(如 http://user-service:8080)访问上游服务时,请求被瞬间拒绝:
curl: (7) Failed to connect to user-service port 8080: Connection refused
检查后端 Pod 状态,所有副本均处于 Running 状态且直接访问 Pod IP 可以正常返回。执行 kubectl get endpoints user-service 检查发现:
NAME ENDPOINTS AGE
user-service <none> 12m
Service 下挂载的端点列表显示为 <none>,说明 kube-proxy 没有在宿主机生成任何 iptables 或 IPVS 转发规则。
核心机制与根因分析
Kubernetes 的 Service 是逻辑抽象,实际流量路由依赖 EndpointController:
- 端点控制器工作模型:EndpointController 持续监听 Service 与 Pod 的生命周期事件。一旦 Service 创建,控制器读取其
spec.selector,并在同命名空间下检索具备相同 Labels 的健康 Pod,将其 IP 和端口注入对应的Endpoints(或EndpointSlice)对象中。 - 出现
<none>的三大诱因:- 标签键值不匹配(Label Mismatch):Service 的 selector 声明为
app: user-api,但 Deployment 的 Pod 模板实际打上的标签是app: user-service或多出了环境变量区分标签; - Pod 探针未就绪(ReadinessProbe 失败):Pod 虽处于 Running,但配置的就绪探针失败,EndpointController 会主动将其从可用端点中剔除;
- 目标端口名称(targetPort)映射错误:Service 中声明了命名的
targetPort: http-web,但容器声明的containerPort名称拼写不同。
- 标签键值不匹配(Label Mismatch):Service 的 selector 声明为
分步排查与定位
1. 比对 Service Selector 与 Pod Labels
# 查看 Service 的选择器
kubectl get svc user-service -o jsonpath='{.spec.selector}'
# 查看后端 Pod 的实际标签
kubectl get pods --show-labels -l app=user-service
如果上述筛选命令返回空,说明 Selector 存在字段或拼写差异。
2. 检查 Pod 的就绪状态(Readiness Status)
kubectl get pods -l app=user-api -o wide
观察 READY 列是否为 0/1。如果容器未就绪,查看详细事件:
kubectl describe pod <pod-name> | grep -E "Readiness probe failed"
针对性解决方案
方案一:校准 Service Selector 与 Pod 模板标签
统一两者标签声明:
apiVersion: v1
kind: Service
metadata:
name: user-service
spec:
selector:
app.kubernetes.io/name: user-service
ports:
- protocol: TCP
port: 8080
targetPort: 8080
确保 Deployment 的 spec.template.metadata.labels 中严格包含 app.kubernetes.io/name: user-service。
方案二:排查并修复 ReadinessProbe 误杀端点
如果是因为业务启动慢导致就绪检查提前超时:
readinessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 15
periodSeconds: 5
failureThreshold: 3
给予足够的初始化等待缓冲,待 Pod 就绪后 Endpoints 会立即自动挂载。


