Kubernetes Deployment and Service YAML example
A Deployment keeps a set number of identical Pods running. A Service gives those Pods one stable address. The two are not linked by name: the Service finds its Pods through labels.
Look at the Service’s selector and the labels in the Deployment’s Pod template. They must be identical, and the Service’s target port must be a port the container listens on. The traffic check below confirms both.
Will traffic reach the Pods?
Service hello:80connects toDeployment hello:80.
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 hello runs 2 Pods, running nginxdemos/hello:0.3.
A Service (hello) gives these Pods a stable cluster-internal address.
Things to know before using it
No livenessProbeDeployment hello
Container "hello" has no livenessProbe. Kubernetes can't detect and restart a hung container. Fix: Add a livenessProbe with httpGet, tcpSocket or exec.
Container may run as rootDeployment hello
Container "hello" doesn't enforce runAsNonRoot. A compromise gives the attacker root inside the container. Fix: Set securityContext.runAsNonRoot: true and runAsUser to a non-zero UID.
allowPrivilegeEscalation not setDeployment hello
Container "hello" doesn't explicitly disable privilege escalation. Defaults to true on older kubelets. Fix: Set securityContext.allowPrivilegeEscalation: false.
Writable root filesystemDeployment hello
Container "hello" doesn't set readOnlyRootFilesystem. Attackers can write tools into / at runtime. Fix: Set securityContext.readOnlyRootFilesystem: true and use volumeMounts for paths that need write access (/tmp, /var/run, ...).
Linux capabilities not droppedDeployment hello
Container "hello" doesn't drop ALL capabilities. By default it runs with ~14 caps including NET_RAW, MKNOD. Fix: Set securityContext.capabilities.drop: ["ALL"] and add only what you need under capabilities.add.
No topology spread or anti-affinityDeployment hello
Deployment "hello" 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
apiVersion: apps/v1
kind: Deployment
metadata:
name: hello
spec:
replicas: 2
selector:
matchLabels:
app: hello
template:
metadata:
labels:
app: hello
spec:
containers:
- name: hello
image: nginxdemos/hello:0.3
ports:
- containerPort: 80
resources:
requests:
cpu: 50m
memory: 64Mi
limits:
cpu: 200m
memory: 128Mi
readinessProbe:
httpGet:
path: /
port: 80
---
apiVersion: v1
kind: Service
metadata:
name: hello
spec:
selector:
app: hello
ports:
- port: 80
Stuck on a Kubernetes concept?
Ask anything and get a narrated visual lesson, pitched at your level. Free.
Try an example