无法通过Service Cluster IP与Pod通信,但Pod IP可正常连通
Kubernetes Service连接失败问题排查与解决
问题现象
- 使用ems Pod的IP地址直接连接gunicorn API正常:
root@nginx:/etc/nginx# curl -v http://10.244.1.155:20000/_ems/plant * Trying 10.244.1.155:20000... * Connected to 10.244.1.155 (10.244.1.155) port 20000 (#0)
- 使用ClusterIP类型的ems-service连接时,出现连接拒绝错误:
root@nginx:/etc/nginx# curl -v http://ems-service.default.svc.cluster.local:20000/_ems/plant; * Trying 10.106.43.2:20000... * connect to 10.106.43.2 port 20000 failed: Connection refused * Failed to connect to ems-service.default.svc.cluster.local port 20000: Connection refused * Closing connection 0 curl: (7) Failed to connect to ems-service.default.svc.cluster.local port 20000: Connection refused
相关资源状态
NAME READY STATUS RESTARTS AGE pod/ems 1/1 Running 0 5m56s pod/nginx 1/1 Running 0 4h46m NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE service/ems-service ClusterIP 10.106.43.2 <none> 20000/TCP 103m
执行kubectl describe service -n default ems-service输出:
Name: ems-service Namespace: default Labels: <none> Annotations: <none> Selector: name=ems Type: ClusterIP IP Family Policy: SingleStack IP Families: IPv4 IP: 10.106.43.2 IPs: 10.106.43.2 Port: <unset> 20000/TCP TargetPort: 80/TCP Endpoints: <none> Session Affinity: None Events: <none>
Pod与Service的YAML配置
ems Pod配置:
apiVersion: v1 kind: Pod metadata: name: ems labels: app: ems spec: containers: - name: ems image: command: ["/bin/sh"] args: ["-c", "chmod +x /root/code/run.sh && /root/code/run.sh"] env: - name: LOGS_DIR value: /root/code/logs imagePullPolicy: Always ports: - containerPort: 20000
ems-service配置:
apiVersion: v1 kind: Service metadata: name: ems-service spec: selector: name: ems ports: - protocol: TCP port: 20000 targetPort: 80
问题原因
从kubectl describe service的输出可见Endpoints:
- 标签不匹配:Service的
selector为name=ems,但ems Pod的labels是app=ems,标签不一致导致Service无法定位目标Pod。 - 端口不匹配:Service的
targetPort设为80,但ems Pod的containerPort为20000,且实际gunicorn API监听在20000端口,端口映射错误会导致流量无法正确转发。
修复方案
修改ems-service的YAML配置,修正标签选择器和目标端口:
apiVersion: v1 kind: Service metadata: name: ems-service spec: selector: app: ems # 与Pod的labels保持一致 ports: - protocol: TCP port: 20000 targetPort: 20000 # 与Pod的containerPort保持一致
修改后执行以下命令更新Service:
kubectl apply -f <修改后的service yaml文件路径>
等待Service重新匹配Pod后,即可通过ems-service.default.svc.cluster.local:20000正常访问API。
内容的提问来源于stack exchange,提问作者Divyank
相关产品推荐
相关产品推荐

