Kubernetes Service port vs targetPort: when targetPort doesn’t match the container
A Service has two port numbers. port is what clients connect to. targetPort is where the traffic is sent on the Pod, and it must be a port the container actually listens on. If targetPort is left out, it defaults to the same value as port.
targetPort can also be a name. In this manifest it is "http", but the container’s port is named "web", so the Service has nowhere to send traffic. Rename either one in the editor, or set targetPort to 8080, and the path connects.
Will traffic reach the Pods?
Service api:80does not reachDeployment api:http. The Service sends traffic to a container port named "http", but no container in Deployment "api" declares a port with that name. Fix: Add name: http to the right entry under the container's ports, or set targetPort to the port number.
What this manifest does
This manifest defines 2 resources in the default namespace: the main thing it runs is 1 Deployment. Let’s walk through it.
Deployment api runs 2 Pods, running myorg/api:1.4.2.
A Service (api) gives these Pods a stable cluster-internal address.
Things to know before using it
No topology spread or anti-affinityDeployment api
Deployment "api" has 2 replicas but no spread rules. All Pods could land on one node, a single failure domain. Fix: Add topologySpreadConstraints or podAntiAffinity to spread across zones/nodes.
The full manifest
# The Service targets a port named "http". The container's port is named "web".
apiVersion: v1
kind: Service
metadata:
name: api
spec:
selector:
app: api
ports:
- port: 80
targetPort: http
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
spec:
replicas: 2
selector:
matchLabels:
app: api
template:
metadata:
labels:
app: api
spec:
containers:
- name: api
image: myorg/api:1.4.2
ports:
- name: web
containerPort: 8080
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 256Mi
securityContext:
runAsNonRoot: true
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
readinessProbe:
httpGet:
path: /ready
port: 8080
livenessProbe:
httpGet:
path: /healthz
port: 8080
Stuck on a Kubernetes concept?
Ask anything and get a narrated visual lesson, pitched at your level. Free.
Try an example