A Service has two ports, and they are easy to mix up.
| Field | Lives in | Means |
|---|---|---|
port | Service | The port clients connect to, on the cluster IP |
targetPort | Service | The port on the Pod the traffic is forwarded to |
containerPort | Pod spec | Documentation of where the container listens. Opens nothing |
kubectl expose --port=80 sets both to 80. Add --target-port=8080 when they differ, or write both in the manifest:
spec:
selector:
app: market-api
ports:
- port: 80
targetPort: 8080Clients say market-api:80; the API listens on 8080; the Service translates.
The silent fault
A wrong targetPort applies without error. The endpoints list looks healthy, because the selector is right. Then:
learner@shallows:~$ kubectl exec client -- wget -qO- market-api:8080/healthz
wget: can't connect to remote host (10.96.191.79): Connection refuseddescribe svc shows the pair:
Port: <unset> 8080/TCP
TargetPort: 9090/TCP
Endpoints: 10.42.0.9:9090Nothing listens on 9090. Compare TargetPort with the container's containerPort or with its logs (listening on :8080).
Named ports
A container port can carry a name, and a Service can target the name:
# in the Pod template # in the Service
ports: ports:
- name: http - port: 80
containerPort: 8080 targetPort: httpChange the number in the template and the Service follows. describe then shows TargetPort: http/TCP.