Kubernetes Service如何处理端口关闭但Pod仍运行的临时离线后端?
Great question—this cuts to the heart of how Kubernetes handles service routing and pod health checks, which is a common point of confusion. Let’s break it down clearly:
默认行为:流量仍会发往该Pod,导致请求失败
Out of the box, Kubernetes Services don’t automatically check if a pod’s application ports are actually listening. Here’s why:
- A Service uses pod label selectors to populate its
Endpointslist. As long as a pod is in theRunningphase and hasn’t been marked asNotReady, it stays in the Endpoints list. - The kube-proxy component routes traffic based on the Endpoints list. If your pod is still running but has stopped listening on port 80, Kubernetes has no way of knowing that by default—it only sees the pod’s lifecycle state (Running), not the health of the application inside it.
- This means new requests will still be routed to the problematic pod, resulting in failed connections (timeouts, connection refused errors, etc.).
如何让Service自动跳过并恢复该实例:配置就绪探针(Readiness Probe)
To fix this, you need to add a Readiness Probe to your Deployment. This probe tells Kubernetes to actively check if your application is ready to serve traffic:
- You can configure it to check port 80 directly (using a TCP socket probe) or send a test HTTP request to a health endpoint (like
/healthz). - If the probe fails (e.g., port 80 is closed), the kubelet will mark the pod as
NotReady. Kubernetes will then remove this pod from the Service’s Endpoints list immediately. - Once the pod resumes listening on port 80, the readiness probe will pass, the pod will be marked
Readyagain, and it will be added back to the Endpoints list. The Service will start routing traffic to it once more.
Here’s a quick example of a readiness probe in a Deployment spec:
apiVersion: apps/v1 kind: Deployment metadata: name: my-app spec: replicas: 3 template: spec: containers: - name: my-container image: my-image:latest ports: - containerPort: 80 readinessProbe: tcpSocket: port: 80 initialDelaySeconds: 5 periodSeconds: 10
This TCP probe checks port 80 every 10 seconds (after an initial 5-second wait). If the port isn’t listening, the pod gets pulled out of service until it recovers.
内容的提问来源于stack exchange,提问作者Tobias Hermann

