Kubernetes Pod与NodePort服务的TCP连接故障排查
问题背景
我创建了名为node-port的Pod和Service,在Pod内部执行nslookup确认DNS解析正常:
root@hello-client:/# nslookup node-port Server: 10.100.0.10 Address: 10.100.0.10#53 Name: node-port.default.svc.cluster.local Address: 10.100.183.19
但从Pod发起TCP连接失败:
root@hello-client:/# curl --trace-ascii - http://node-port.default.svc.cluster.local:3050 == Info: Trying 10.100.183.19:3050...
一、连接失败的可能原因
- Service端口配置错误:Service的
targetPort未匹配Pod的监听端口,或port字段设置错误,导致流量无法转发到Pod。 - Pod状态异常:Pod处于
CrashLoopBackOff、Pending或NotReady状态,容器内服务未启动。 - 服务监听地址错误:Pod内服务仅绑定
localhost(127.0.0.1),而非0.0.0.0,无法接收Service转发的流量。 - NetworkPolicy限制:集群中存在网络策略,禁止
hello-clientPod与node-portPod/Service的TCP通信。 - Service端点未就绪:Service的
Endpoints列表为空,标签选择器配置错误,未匹配到可用Pod。 - CNI插件故障:Calico、Flannel等网络插件异常,导致Pod与Service间流量无法转发。
- 防火墙/安全组拦截:节点防火墙(iptables、firewalld)或云平台安全组阻止了相关端口的流量。
二、排查建议
检查Service配置
- 执行
kubectl describe service node-port,确认Spec.Ports的port、targetPort与Pod服务端口一致,标签选择器Selector匹配Pod标签。 - 执行
kubectl get endpoints node-port,查看是否有可用端点,为空则说明标签匹配错误或Pod未就绪。
- 执行
验证Pod状态与服务
- 执行
kubectl get pods -l <service-selector>(替换为Service的标签选择器),确认Pod状态为Running,重启次数无异常。 - 执行
kubectl logs <pod-name>,查看容器日志,确认服务是否正常启动。 - 进入Pod内部,执行
netstat -tulpn或ss -tulpn,确认服务在0.0.0.0:<targetPort>上监听。
- 执行
测试网络连通性
- 从
hello-clientPod直接连接Pod IP与端口:curl <pod-ip>:<targetPort>,连通则问题在Service层,不通则Pod内服务或网络有问题。 - 执行
kubectl get networkpolicies,查看是否有相关限制策略,必要时临时删除测试。
- 从
检查集群网络组件
- 查看CNI插件Pod状态:如
kubectl get pods -n kube-system -l k8s-app=calico-node,确认组件正常运行。 - 检查节点iptables规则:
iptables-save | grep node-port,确认Service转发规则存在且正确。
- 查看CNI插件Pod状态:如
排查防火墙与安全组
- 在节点执行
iptables -L -n,确认无拦截Pod间流量或Service端口的规则。 - 云平台集群检查节点安全组,确保允许集群内部TCP流量(如Pod CIDR范围)。
- 在节点执行
正常集群中的预期执行结果
/ # curl --trace-ascii - node-port:3050 == Info: Trying 10.100.13.83:3050... == Info: Connected to node-port (10.100.13.83) port 3050 (#0) => Send header, 78 bytes (0x4e) 0000: GET / HTTP/1.1 0010: Host: node-port:3050 0026: User-Agent: curl/7.83.1 003f: Accept: */* 004c: == Info: Mark bundle as not supporting multiuse <= Recv header, 17 bytes (0x11) 0000: HTTP/1.1 200 OK <= Recv header, 38 bytes (0x26) 0000: Server: Werkzeug/2.2.2 Python/3.8.13 <= Recv header, 37 bytes (0x25) 0000: Date: Fri, 26 Aug 2022 04:34:48 GMT <= Recv header, 32 bytes (0x20) 0000: Content-Type: application/json <= Recv header, 20 bytes (0x14) 0000: Content-Length: 25 <= Recv header, 19 bytes (0x13) 0000: Connection: close <= Recv header, 2 bytes (0x2) 0000: <= Recv data, 25 bytes (0x19) 0000: {. "hello": "world".}. { "hello": "world" } == Info: Closing connection 0 / #
内容的提问来源于stack exchange,提问作者Senthil Kumaran
相关产品推荐
相关产品推荐

