Show contents
Chapter 1 of 7 · 20 min
Pods and Deployments: the desired state
By the end of this chapter, you'll be able to
- Explain what a container orchestrator does and why it is needed
- Describe a pod, a Deployment and the role of labels
- Read and write a Deployment's YAML manifest
- Explain the reconciliation loop between desired and actual state
Why an orchestrator?
Docker runs containers on one machine. In production, you have several machines (nodes) and changing needs: spreading containers, restarting them when they crash, adding more when traffic rises, updating without downtime. An orchestrator handles all of this for a cluster (a group of nodes). Kubernetes (often shortened to K8s) is today the most widely used orchestrator, with all the major cloud providers as well as on servers installed on site.
The pod: the smallest unit
Kubernetes does not manage containers directly, but pods. A pod groups one or more containers that share the same network address and can share files. In the vast majority of cases, a pod contains a single container: your application's.
A pod is ephemeral: if it dies (failed node, crash), it is not repaired, it is replaced by a new pod, with another name and another address. So you almost never create a pod by hand.
The Deployment: the desired state
A Deployment describes an application's desired state: which image to run, how many copies (replicas), with which settings. You write it in a manifest in YAML format:
apiVersion: apps/v1
kind: Deployment
metadata:
name: payment-api
spec:
replicas: 3
selector:
matchLabels:
app: payment-api
template:
metadata:
labels:
app: payment-api
spec:
containers:
- name: api
image: registry.example.com/payment-api:1.4.2
ports:
- containerPort: 8000
replicas: 3: we want 3 identical pods;template: the model for each pod (its labels and containers);selector.matchLabels: how the Deployment recognises its pods. A label is akey: valuetag; here, every pod carryingapp: payment-apibelongs to it.
You send the manifest to the cluster with kubectl, the Kubernetes command-line tool:
kubectl apply -f payment-api.yaml
kubectl get deployments
kubectl get pods -l app=payment-api
The reconciliation loop
At the heart of Kubernetes, controllers run in a loop: they compare the desired state (what the manifests say) with the actual state (what is really running), and act to reduce the gap. This is reconciliation. Here is a simplified simulation in Python:
desired = {"api": 3, "worker": 2}
actual = {"api": ["api-1"], "worker": ["worker-1", "worker-2", "worker-3"]}
counter = {"api": 1, "worker": 3}
for round_ in range(1, 3):
actions = []
for name, n in desired.items():
pods = actual[name]
while len(pods) < n:
counter[name] += 1
pods.append(f"{name}-{counter[name]}")
actions.append(f"create {pods[-1]}")
while len(pods) > n:
actions.append(f"delete {pods.pop()}")
print(f"round {round_}:", ", ".join(actions) if actions else "nothing to do")
print(actual)
round 1: create api-2, create api-3, delete worker-3
round 2: nothing to do
{'api': ['api-1', 'api-2', 'api-3'], 'worker': ['worker-1', 'worker-2']}
The controller does not remember a list of orders: on every round, it looks at reality. If a pod dies between two rounds, the next round replaces it. This is what makes Kubernetes self-healing.
The actual state matches the desired state again, with no human action.
Text description of the animation
- Three pods are running, spread over three nodes.
- Node 2 fails: the api-b pod disappears with it.
- On the next round, the Deployment's controller counts two pods instead of three.
- It creates a new pod; the scheduler places it on a node with room.
- The actual state matches the desired state again, with no human action.
Mini-lab: simulate a failurePython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: checking a manifest
Before sending a manifest to the cluster, a team wants a small checker. Write check(manifest) that takes a Deployment as a Python dictionary and returns the list of problems: fewer than 2 replicas, a selector that differs from the template's labels, an image without a precise version (no : or :latest).
manifest = {
"kind": "Deployment",
"spec": {
"replicas": 1,
"selector": {"matchLabels": {"app": "api"}},
"template": {
"metadata": {"labels": {"app": "payment-api"}},
"spec": {"containers": [{"name": "api", "image": "payment-api:latest"}]},
},
},
}
Hint 1
manifest["spec"]["replicas"], the selector in spec["selector"]["matchLabels"], the labels in spec["template"]["metadata"]["labels"].Hint 2
labels.get(key) == value. For the image, ":" not in image or image.endswith(":latest").Show the solution and common mistakes
def check(manifest):
problems = []
spec = manifest["spec"]
if spec.get("replicas", 1) < 2:
problems.append("fewer than 2 replicas: no tolerance to failure")
labels = spec["template"]["metadata"]["labels"]
for key, value in spec["selector"]["matchLabels"].items():
if labels.get(key) != value:
problems.append(f"selector {key}={value} missing from the template labels")
for c in spec["template"]["spec"]["containers"]:
image = c["image"]
if ":" not in image or image.endswith(":latest"):
problems.append(f"image without a precise version: {image}")
return problems
manifest = {
"kind": "Deployment",
"spec": {
"replicas": 1,
"selector": {"matchLabels": {"app": "api"}},
"template": {
"metadata": {"labels": {"app": "payment-api"}},
"spec": {"containers": [{"name": "api", "image": "payment-api:latest"}]},
},
},
}
for p in check(manifest):
print("-", p)
- fewer than 2 replicas: no tolerance to failure
- selector app=api missing from the template labels
- image without a precise version: payment-api:latest
latest is a moving tag: two nodes may download two different versions of "the latest" image. A precise version (1.4.2) guarantees that every pod runs the same code.
Common mistakes:
- Comparing whole dictionaries (
selector == labels): labels can legitimately hold more than the selector. - Forgetting that a pod can have several containers: you must go through the whole
containerslist.
Summary
- 1An orchestrator spreads containers over a cluster, restarts them and adapts them to traffic.
- 2A pod is the basic unit: one or more containers, ephemeral, replaced rather than repaired.
- 3A Deployment describes the desired state (image, replicas); its pods are recognised by their labels.
- 4Controllers constantly reconcile the actual state with the desired state: this is what makes Kubernetes self-healing.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.