Lesson 17 · Section 2: Core Concepts
Lesson 17: ReplicaSets: keeping the right number of Pods alive
What a ReplicaSet is, how its control loop counts and replaces Pods, how labels and owner references tie the two together, and how to create, scale, fix and debug one quickly. · 17 min read · 4 min video
Official competencies this lesson covers
Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.
Why ReplicaSets exist
A Pod on its own is a one-off. The kubelet restarts its containers when they crash, but nothing recreates the Pod itself: delete it, drain its node or lose the node, and the application is gone until somebody notices. A single Pod also gives you one point of failure and no way to spread load.
A ReplicaSet is the object that turns "run this Pod" into "always keep N of these Pods running". You state the number, and a controller in the control plane creates Pods when there are too few and deletes Pods when there are too many, for as long as the ReplicaSet exists.
That one sentence explains almost every surprising thing a ReplicaSet does, so keep it in mind through the rest of this lesson.
What a ReplicaSet is made of
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: web
namespace: shop
spec:
replicas: 3
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: nginx
image: nginx:1.29-alpine
| Field | Meaning | Good to know |
|---|---|---|
spec.replicas | How many Pods you want | Defaults to 1. The only field you change often. |
spec.selector | Which Pods count as replicas | Required, and immutable after creation. Supports matchLabels and matchExpressions. |
spec.template | The Pod to create when one is missing | Everything under it is an ordinary Pod: metadata plus spec, without apiVersion or kind. |
Two rules tie the fields together:
- The template's labels must satisfy the selector. Otherwise the ReplicaSet would create Pods it could not count,
and it would create them forever. The API server rejects such an object:
The ReplicaSet "web" is invalid: ... `selector` does not match template `labels`. - The template's
restartPolicymust beAlways(the default). A ReplicaSet is for Pods that should run forever; run-to-completion work belongs in a Job.
The ReplicaSet reports back in status, which is what kubectl get rs prints:
| Column | Status field | Meaning |
|---|---|---|
DESIRED | spec.replicas | What you asked for |
CURRENT | status.replicas | Pods that exist and match the selector, ready or not |
READY | status.readyReplicas | Pods that pass their readiness probe |
How it works: the reconcile loop
Parts:
- You (kubectl apply)
- RS controller (controller-manager)
- ReplicaSet web (replicas: 3)
- Pod web-7k2xq (Running)
- Pod web-m9d4c (Running)
- Pod web-p5c7t (lost with its node)
- Pod web-zr8wh (replacement)
Connections:
- You to ReplicaSet web: desired
- RS controller to ReplicaSet web: watches
- ReplicaSet web to Pod web-7k2xq
- ReplicaSet web to Pod web-m9d4c: owns
- ReplicaSet web to Pod web-p5c7t
- Pod web-p5c7t to Pod web-zr8wh: replaced
No part of a ReplicaSet runs on your nodes. The object is only a record in etcd. The work is done by the
ReplicaSet controller, one of the many loops inside kube-controller-manager on the control plane. It watches
ReplicaSets and Pods through the API server, and every time either changes it runs the same small calculation for
the ReplicaSet involved:
- List Pods matching the selector
- Ignore Pods that are terminating or finished
- Compare the count with spec.replicas
- Too few: create Pods from the template
- Too many: delete the surplus
- Write the counts to status
This is the pattern behind all of Kubernetes: you record the desired state, and a controller keeps nudging the
actual state towards it. It is why the same mechanism handles a first deployment, a crashed node, a deleted Pod
and a kubectl scale without any special cases. In each one the count is simply wrong, and the controller corrects
it.
Note what the controller does not do. It does not start containers (the kubelet does), it does not pick nodes
(the scheduler does) and it does not repair a broken Pod. It creates Pod objects through the API server, like you
would with kubectl, and the rest of the cluster takes it from there. A Pod that is lost is not brought back; a
new Pod with a new name and a new IP takes its place.
Under the hood · What counts as a replica, and how fast lost Pods come back
- A Pod counts if it matches the selector, is owned by this ReplicaSet, is not being deleted and has not finished
(phase
SucceededorFailed). It does not have to be ready or even scheduled. A Pod stuck inPendingorCrashLoopBackOffis still a replica, so the ReplicaSet will not replace it. - A Pod you delete is replaced within a second or two, because the delete is an event the controller sees at once.
- A Pod on a node that stops responding takes much longer. The node is first marked
NotReady, and Pods tolerate that for 300 seconds by default before they are evicted. Only then does the count drop and a replacement appear, so expect about five minutes. That delay is a setting on the Pod (tolerationSeconds), not on the ReplicaSet. - When many Pods are missing the controller creates them in growing batches (1, then 2, then 4, and so on). If the
first creations fail, for example against a ResourceQuota, it stops early instead of sending hundreds of requests
that would fail the same way, and it records a
FailedCreateevent on the ReplicaSet.
Labels select, owner references own
Parts:
- ReplicaSet web (selector app=web)
- Pod web-7k2xq (app=web)
- Pod web-m9d4c (app=web)
- Pod handmade (app=web, no owner)
- Pod web-p5c7t (app=debug, released)
Connections:
- ReplicaSet web to Pod web-7k2xq: owner
- ReplicaSet web to Pod web-m9d4c: owner
- ReplicaSet web to Pod handmade: adopts
Two different links connect a ReplicaSet and its Pods, and it helps to keep them apart:
- The selector answers "which Pods could be mine?". It is a label query, evaluated in the ReplicaSet's own namespace.
- The owner reference answers "which Pods are mine?". Every Pod the controller creates gets a
metadata.ownerReferencesentry that names the ReplicaSet, withcontroller: true. You see it inkubectl describe podasControlled By: ReplicaSet/web.
Three behaviours follow, and each can cost or save you time:
| Situation | What the ReplicaSet does |
|---|---|
| A Pod matches the selector and has no controller owner | It adopts the Pod (adds the owner reference) and counts it. |
| An owned Pod's labels stop matching the selector | It releases the Pod (removes the owner reference) and creates a replacement. The released Pod keeps running. |
| The ReplicaSet is deleted | The garbage collector deletes every Pod that names it as owner, unless you ask it not to. |
The same rule is why two ReplicaSets (or a ReplicaSet and a Deployment) should never share a selector. Kubernetes does not stop you, and the owner references keep them from stealing each other's Pods, but any Pod without an owner will be picked up by whichever controller sees it first.
ReplicaSets and Deployments
Parts:
- Deployment web (you edit this)
- RS web-5d8f7c9b6 (replicas: 3)
- RS web-64c8d5f7d (replicas: 0)
- Pod (web-5d8f7c9b6-x7k2p)
- Pod (web-5d8f7c9b6-b4n6s)
- Pod (web-5d8f7c9b6-q9t2v)
Connections:
- Deployment web to RS web-5d8f7c9b6: current
- Deployment web to RS web-64c8d5f7d: previous
- RS web-5d8f7c9b6 to Pod
- RS web-5d8f7c9b6 to Pod
- RS web-5d8f7c9b6 to Pod
A ReplicaSet cannot update its Pods. If you change the image in the template, the count is still correct, so the controller does nothing; the running Pods keep the old image until something deletes them.
That gap is what a Deployment fills. A Deployment owns ReplicaSets the way a ReplicaSet owns Pods. For every
version of the Pod template it creates one ReplicaSet, named after the Deployment plus a hash of the template (for
example web-5d8f7c9b6), and adds the same hash to the selector and the Pods as the pod-template-hash label. A
rolling update is nothing more than scaling the new ReplicaSet up while scaling the old one down. The old one is kept
at zero replicas, which is what makes kubectl rollout undo possible.
| You want | Use |
|---|---|
| A stateless app that you will update | Deployment (it manages the ReplicaSets) |
| Exactly one Pod per node | DaemonSet |
| Stable names and storage per Pod | StatefulSet |
| Work that runs to completion | Job |
| A fixed set of Pods that is never rolled, or a custom update tool of your own | A bare ReplicaSet (rare) |
So why learn ReplicaSets at all? Because every Deployment problem you debug ends at one. The Pods' names, their
owner, the DESIRED / CURRENT / READY numbers and the events that explain a missing Pod all live on the ReplicaSet.
Using it
Example · Create a ReplicaSet and watch it heal
Save the manifest above as web-rs.yaml, create it, then delete a Pod and watch the count recover.
kubectl create namespace shop
kubectl apply -f web-rs.yaml
kubectl -n shop get rs web # DESIRED 3, CURRENT 3, READY 3
kubectl -n shop get pods -l app=web # web-7k2xq, web-m9d4c, web-p5c7t
kubectl -n shop delete pod web-p5c7t
kubectl -n shop get pods -l app=web # still three: a new name has appeared
kubectl -n shop describe rs web # Events: SuccessfulCreate ... Created pod: web-zr8wh
The Pod names are the ReplicaSet's name plus five random characters. The events at the bottom of
kubectl describe rs are the controller's own log of every Pod it created or deleted.
Example · Scale up and down
Three ways to change the number, from fastest to slowest:
kubectl -n shop scale rs web --replicas=5 # imperative, one line
kubectl -n shop edit rs web # change spec.replicas in the editor
kubectl apply -f web-rs.yaml # after editing replicas in the file
kubectl scale changes the live object only. If the task says the manifest file must reflect the change, edit the
file too, or the next kubectl apply -f will put the old number back.
Example · Fix a ReplicaSet whose Pods never become ready
A typical troubleshooting task: ReplicaSet api in namespace shop should run four Pods, but none is ready.
kubectl -n shop get rs api # DESIRED 4, CURRENT 4, READY 0
kubectl -n shop get pods -l app=api # ImagePullBackOff on all four
kubectl -n shop describe pod -l app=api | grep -i -A3 failed
The image tag has a typo. Fix the template, then replace the Pods, because the template change alone does nothing for Pods that already exist:
kubectl -n shop set image rs/api api=nginx:1.29-alpine
kubectl -n shop delete pod -l app=api
kubectl -n shop get rs api # READY climbs back to 4
The broken Pods still counted as replicas, which is why the ReplicaSet never replaced them on its own.
Example · Take one Pod out of rotation without losing it
One replica misbehaves and you want to inspect it, without it serving traffic and without running one short.
kubectl -n shop label pod web-7k2xq app=debug --overwrite
kubectl -n shop get pods -L app # web-7k2xq now app=debug, plus one new web Pod
The Pod no longer matches the selector, so the ReplicaSet releases it and creates a replacement. Any Service that
selects app: web stops sending it traffic for the same reason. The Pod keeps running with no owner: delete it
yourself when you are done.
Tricks
Under the hood · Which Pods go first when you scale down
When there are too many Pods, the controller ranks them and deletes from the top of this list:
- Pods that are not scheduled yet, then Pods that are still
Pending - Pods that are not ready
- Pods with a lower
controller.kubernetes.io/pod-deletion-costannotation (the default is 0) - Pods on nodes that hold more replicas of this ReplicaSet, which keeps the rest spread out
- Pods that became ready more recently, and then the newest Pods
So scaling down removes the least useful Pods first, and among healthy Pods roughly the youngest. To protect a
particular Pod, give the others a lower deletion cost: kubectl annotate pod web-m9d4c controller.kubernetes.io/pod-deletion-cost=-100 makes that Pod the first to go.
Common mistakes
- Editing the template and expecting a rollout. Existing Pods are not touched. Delete them, or use a Deployment.
- Scaling a ReplicaSet that a Deployment owns. The Deployment sets it straight back. Scale the Deployment.
- Selector and template labels that differ. The API server rejects the object, so read the error instead of retyping the whole file. With the generated manifest from the trick above it cannot happen.
- A selector that is too broad.
app: webin a namespace where other Pods carry that label means adopted Pods and deleted "extras". Give each workload its own label value. - Deleting Pods to stop an application. They come back. Scale to zero (
--replicas=0) or delete the ReplicaSet. - Looking for
kubectl rollouton a ReplicaSet.rollout status,undoandrestartwork on Deployments, DaemonSets and StatefulSets, not on a ReplicaSet.
Recap
- A ReplicaSet keeps the number of Pods matching its selector equal to
spec.replicas, by creating Pods from its template or deleting the surplus. - The work is done by a reconcile loop in
kube-controller-manager; lost Pods are replaced, never repaired. - Labels decide which Pods can belong;
ownerReferencesrecord which do. Matching bare Pods are adopted, relabelled Pods are released. - The template only applies to new Pods. Updating running Pods is what a Deployment adds, using one ReplicaSet per template version.
- In the exam:
kubectl get rs -o wide,kubectl scale rs,kubectl describe rsforFailedCreate, and generate the YAML fromkubectl create deployment --dry-run=client -o yaml.
Official docs
Quiz: check what you learned
5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.
Sign in to take the quiz and keep your score.
Practise: try it on a real cluster
A hands-on lab for this lesson. You get goals, not steps: any solution that reaches them passes.
Scale one ReplicaSet for a busy weekend and repair another whose Pods never become ready.
Fix · Level 2 · standard · target 15 min
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.