ReplicaSets
One notes-web pod is one crash away from an outage. You want three, always. The object whose single job is "keep N identical pods alive" is the ReplicaSet.
The rule
A ReplicaSet counts pods by label and fixes the count.
A ReplicaSet has three key parts:
replicas— how many pods should exist.selector— which labels mark "my" pods.template— the pod recipe used to make new ones. Its labels must match the selector.
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: notes-web
namespace: notes
spec:
replicas: 3
selector:
matchLabels:
app: notes-web
template:
metadata:
labels:
app: notes-web
spec:
containers:
- name: web
image: ghcr.io/example/notes-web:1.2The ReplicaSet does not remember pod names. It simply counts running pods whose labels match the selector. Too few? It creates more from the template. Too many? It deletes some.
Notice what a ReplicaSet does not do: if you edit its template — say, to image 1.3 — the three running pods keep running 1.2. The template is only used when a new pod is needed. A ReplicaSet keeps a count; it has no idea how to change versions.
In practice you rarely write a ReplicaSet yourself. A Deployment creates and manages ReplicaSets for you, adding safe updates on top. But the counting behaviour you see every day is the ReplicaSet's.
The shortcut
Whenever pods appear or vanish unexpectedly, count by label: how many pods match the selector, and what does replicas say?
Delete one
You delete a notes-web pod. Pods with
app: notes-web: 2. Wanted: 3. The ReplicaSet creates one.
That last trick is useful: relabelling pulls a misbehaving pod out of the count so you can inspect it while a healthy replacement takes its place.
Drills
Answer fast — trust the rule.
How does a ReplicaSet decide which pods belong to it?
The template's labels are app: web but the selector asks for app: notes-web. What happens?
replicas: 3, and you create a fourth matching pod by hand. What happens?
Why do you usually not create ReplicaSets directly?
Remember
- A ReplicaSet counts pods by label and fixes the count.
- Template labels must match the selector.
- Trap: stray pods with matching labels get adopted — or deleted.
