Skip to content
LF Cert Trainer

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

1/10ReplicaSets
0:00 / 3:54

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
FieldMeaningGood to know
spec.replicasHow many Pods you wantDefaults to 1. The only field you change often.
spec.selectorWhich Pods count as replicasRequired, and immutable after creation. Supports matchLabels and matchExpressions.
spec.templateThe Pod to create when one is missingEverything 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 restartPolicy must be Always (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:

ColumnStatus fieldMeaning
DESIREDspec.replicasWhat you asked for
CURRENTstatus.replicasPods that exist and match the selector, ready or not
READYstatus.readyReplicasPods that pass their readiness probe

How it works: the reconcile loop

The reconcile loopdesiredwatchesownsreplacedYoukubectl applyRS controllercontroller-managerReplicaSet webreplicas: 3Pod web-7k2xqRunningPod web-m9d4cRunningPod web-p5c7tlost with its nodePod web-zr8whreplacement
The reconcile loop. The controller compares the number of matching Pods with spec.replicas and creates or deletes Pods until they agree. A lost Pod is not repaired: a new one takes its place.

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:

  1. List Pods matching the selector
  2. Ignore Pods that are terminating or finished
  3. Compare the count with spec.replicas
  4. Too few: create Pods from the template
  5. Too many: delete the surplus
  6. Write the counts to status
One pass of the loop

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 Succeeded or Failed). It does not have to be ready or even scheduled. A Pod stuck in Pending or CrashLoopBackOff is 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 FailedCreate event on the ReplicaSet.

Labels select, owner references own

Labels select, owner references ownownerowneradoptsReplicaSet webselector app=webPod web-7k2xqapp=webPod web-m9d4capp=webPod handmadeapp=web, no ownerPod web-p5c7tapp=debug, released
Labels select, owner references own. The selector decides which Pods could belong to the ReplicaSet; the ownerReference on each Pod records that they do. A matching Pod without an owner is adopted, and a Pod whose label changes is released.

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.ownerReferences entry that names the ReplicaSet, with controller: true. You see it in kubectl describe pod as Controlled By: ReplicaSet/web.

Three behaviours follow, and each can cost or save you time:

SituationWhat the ReplicaSet does
A Pod matches the selector and has no controller ownerIt adopts the Pod (adds the owner reference) and counts it.
An owned Pod's labels stop matching the selectorIt releases the Pod (removes the owner reference) and creates a replacement. The released Pod keeps running.
The ReplicaSet is deletedThe 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

A Deployment manages ReplicaSets, a ReplicaSet manages PodscurrentpreviousDeployment webyou edit thisRS web-5d8f7c9b6replicas: 3RS web-64c8d5f7dreplicas: 0Podweb-5d8f7c9b6-x7k2pPodweb-5d8f7c9b6-b4n6sPodweb-5d8f7c9b6-q9t2v
A Deployment manages ReplicaSets, a ReplicaSet manages Pods. Each version of the Pod template gets its own ReplicaSet. A rollout scales the new one up and the old one down; the old one stays at zero replicas so you can roll back.

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 wantUse
A stateless app that you will updateDeployment (it manages the ReplicaSets)
Exactly one Pod per nodeDaemonSet
Stable names and storage per PodStatefulSet
Work that runs to completionJob
A fixed set of Pods that is never rolled, or a custom update tool of your ownA 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:

  1. Pods that are not scheduled yet, then Pods that are still Pending
  2. Pods that are not ready
  3. Pods with a lower controller.kubernetes.io/pod-deletion-cost annotation (the default is 0)
  4. Pods on nodes that hold more replicas of this ReplicaSet, which keeps the rest spread out
  5. 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: web in 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 rollout on a ReplicaSet. rollout status, undo and restart work 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; ownerReferences record 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 rs for FailedCreate, and generate the YAML from kubectl 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.