Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 78 ยท Workloads

ReplicaSets

Learn how a Kubernetes ReplicaSet keeps a set number of identical pods alive, how selectors and ownerReferences work, and why you rarely create one yourself.

A single pod is fragile. If its node dies, or someone deletes it, the pod is gone and nothing brings it back. Real services need several identical copies running at once, both for capacity and so that losing one copy does not mean an outage. A ReplicaSet is the object that provides this: you tell it "I want 3 pods that look like this", and it keeps exactly 3 of them alive, creating new ones when some disappear and deleting extra ones when there are too many.

A ReplicaSet is a small, focused controller. It does not know about versions, rollouts or rollbacks; that is the job of a Deployment, which owns ReplicaSets for you. Still, understanding ReplicaSets matters, because every Deployment you ever run is really a stack of ReplicaSets, and the way they find and adopt pods explains many puzzling behaviors.

What a ReplicaSet holds

replicas How many pods you want.
selector Which pods count as mine.
template How to build a new pod.

Count, selector and template are the whole object.

1 / 2

A ReplicaSet manifest

Here is a complete ReplicaSet. Read-only, because the site has no cluster to apply it to.

YAML
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: web
  labels:
    app: web
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: web
          image: nginx:1.27
          ports:
            - containerPort: 80

Three parts matter:

  • spec.replicas is the desired number of pods. If you omit it, the default is 1.
  • spec.selector says which pods this ReplicaSet manages. It is a label query, exactly the kind you met in labels and selectors.
  • spec.template is a pod blueprint, with its own metadata and spec. Whenever the ReplicaSet needs a new pod, it stamps one out from this template.

The selector and the template labels must agree. If the template's labels do not satisfy the selector, the API server rejects the ReplicaSet, because it would create pods it could never count. The selector is also immutable after creation in apps/v1, so choose it carefully.

The reconcile loop

A ReplicaSet does not "run" pods. It runs a loop that compares two numbers and acts on the difference:

  1. List all pods in the namespace whose labels match the selector and that are not being deleted.
  2. If there are fewer than replicas, create the missing ones from the template.
  3. If there are more, delete the surplus.
  4. Repeat whenever a pod or the ReplicaSet changes.

This is level-triggered logic: the controller does not care why the count is wrong (a crash, a manual delete, a node failure). It only looks at the current level and moves toward the target. That is why ReplicaSets recover from almost anything without special cases. More on this pattern in Controllers and the reconcile loop.

The TryIt below is a stand-in for the real controller. It is plain Python, not Kubernetes code, but the logic is the same: observe, compare, act. Everything is deterministic, so the output is stable.

Python A ReplicaSet reconcile loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Study the third step. A pod named stray that happens to carry app: web was counted and then one pod was deleted to make room. A real ReplicaSet behaves the same way, which leads to the next section.

Ownership and adoption

Every pod created by a ReplicaSet carries an ownerReference in its metadata that points back at the ReplicaSet:

YAML
metadata:
  name: web-7c9d8f5b6-4xk2p
  ownerReferences:
    - apiVersion: apps/v1
      kind: ReplicaSet
      name: web-7c9d8f5b6
      uid: 8f3c1d2e-...
      controller: true
      blockOwnerDeletion: true

Owner references drive two behaviors:

  • Garbage collection. When you delete a ReplicaSet, the garbage collector deletes the pods it owns. You can keep the pods by deleting with --cascade=orphan.
  • Adoption and conflict avoidance. A ReplicaSet only manages matching pods that either have no controller or are already owned by it. A matching pod owned by another controller is ignored, so two ReplicaSets with overlapping selectors do not fight over the same pod.

A bare pod (with no owner) that matches a ReplicaSet's selector is adopted: the ReplicaSet adds itself as owner. This is a classic trap. If you create a stand-alone pod with app: web while a ReplicaSet for app: web already has its full count, the new pod is adopted and the ReplicaSet immediately deletes one pod to get back to the target. Which one it picks is decided by a ranking rule that prefers deleting pods that are not yet scheduled, not ready, or newer.

Never create two controllers whose selectors overlap on the same labels. Even with ownerReferences protecting existing pods, new pods can be adopted by the wrong controller and counts become confusing. Give each workload a unique label such as app.kubernetes.io/name plus an instance label.

The next stand-in models ownership: pods have an owner, and each controller only counts pods it owns or that are free to adopt.

Python Adoption and owner references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Scaling and self-healing

You change the count with kubectl scale, by editing the manifest and applying it, or through an autoscaler (see the Horizontal Pod Autoscaler). Typical read-only commands:

Terminal
kubectl get replicaset
kubectl scale replicaset web --replicas=5
kubectl describe replicaset web
kubectl delete replicaset web --cascade=orphan   # keep the pods

kubectl get replicaset prints columns DESIRED, CURRENT and READY. DESIRED is spec.replicas; CURRENT is how many pods exist; READY is how many pass their readiness probe. If CURRENT is right but READY is low, the pods exist but are not healthy, and no amount of reconciling by the ReplicaSet will fix it: it counts existing pods, not working ones.

Self-healing has limits. The ReplicaSet recreates a pod that was deleted or whose node vanished, but a pod that keeps crashing is the kubelet's problem (it restarts containers in place, see pod lifecycle). And if there is no node with enough resources, the new pod stays Pending and the ReplicaSet can do nothing more.

Why you rarely create one directly

A ReplicaSet gives you the right number of identical pods, but no way to change what those pods run. If you edit spec.template (say a new image tag), existing pods are untouched: the template only applies to pods created later. To roll out a new version you would have to create a second ReplicaSet, scale it up, scale the old one down and watch for problems, all by hand.

A Deployment automates exactly that. It creates a ReplicaSet per version of the pod template, scales them against each other for a rolling update, and keeps old ones for rollbacks. So the rule of thumb is: use a Deployment for stateless apps, a StatefulSet for stateful ones, a DaemonSet for per-node agents, and treat ReplicaSets as an implementation detail you can read when debugging (kubectl get rs).

The old ReplicationController is the predecessor of ReplicaSet. It only supports equality-based selectors and is not recommended for new work.

ReplicationController: the legacy ancestor

Before ReplicaSets there was the ReplicationController (RC). You will still meet it in old manifests, old books and some exam questions. It does the same core job, keeping a number of identical pods running, with an older selector syntax:

ReplicationController ReplicaSet
API v1 (core group) apps/v1
Selector Equality only: a plain map of labels matchLabels and set-based matchExpressions (In, NotIn, Exists)
Selector optional? Defaults to the template's labels Required, and must match the template
Used by Deployments No Yes
Rolling updates Client-side kubectl rolling-update, which was removed Driven by a Deployment
YAML
apiVersion: v1
kind: ReplicationController
metadata:
  name: web
spec:
  replicas: 3
  selector:
    app: web             # a plain map, not matchLabels
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: web
          image: nginx:1.27

Everything else works the same way: kubectl get rc, kubectl scale rc web --replicas=5, kubectl delete rc web. The practical advice is simple: do not write new RCs. Use a Deployment, which creates and manages ReplicaSets for you. If you inherit an RC, convert it by changing kind and apiVersion to apps/v1 ReplicaSet (or better, a Deployment) and rewriting the selector as matchLabels.

Isolating a pod by changing its label

Because a ReplicaSet or RC finds its pods by label, you can pull one pod out of the group without deleting it. This is a classic debugging trick: a pod misbehaves, you want to examine it, but you also want production to keep its full capacity.

Terminal
kubectl label pod web-7c9d8f5b6-4xk2p app=web-debug --overwrite

The pod no longer matches the selector, so the controller releases it (it removes the ownerReference) and notices it is one pod short, so it creates a replacement. The Service selects by label too, so the isolated pod also stops receiving traffic, but it keeps running, and you can kubectl exec, read its logs and attach debuggers to it (Debugging Applications in a Cluster). When you are done, delete the pod. It is now an unmanaged pod, and nothing will bring it back. If you want a pod to rejoin the group instead, set the label back before you delete anything.

Python Isolating a pod with a label change

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Deleting a controller but keeping its pods

The opposite move is deleting the controller while leaving the pods running, using --cascade=orphan (shown earlier). Typical uses are replacing a controller with a different definition without restarting anything, or migrating an RC to a ReplicaSet:

Terminal
kubectl delete rc web --cascade=orphan      # the three pods keep running, now ownerless
kubectl apply -f web-replicaset.yaml        # a new controller whose selector matches them
kubectl get rs web -o wide                  # DESIRED 3, CURRENT 3: it adopted the pods

The new controller adopts pods whose labels match its selector and that have no owner, so it creates nothing new. If its selector matched more pods than it wants, it would delete the surplus, so check the selector carefully. Without a matching controller, orphaned pods are just unmanaged pods: nothing replaces them if they die.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A ReplicaSet has replicas: 3 and one of its pods is deleted. What happens?

    The ReplicaSet controller notices fewer matching pods than desired and creates a new one from spec.template. The kubelet only restarts containers inside an existing pod.
  2. 2. You edit the image in a ReplicaSet's pod template. What happens to the existing pods?

    A ReplicaSet does not perform updates. It only uses the template when it creates pods, which is why Deployments exist.
  3. 3. A bare pod with labels matching a full ReplicaSet's selector is created. What does the ReplicaSet do?

    Pods with no controller that match the selector are adopted through an ownerReference. The count is then too high, so the ReplicaSet deletes one.
  4. 4. What does deleting a ReplicaSet with --cascade=orphan do?

    Orphan cascading removes the owner only. The pods lose their ownerReference and keep running.

Summary

  • A ReplicaSet keeps a desired number of identical pods running, using a replica count, a label selector and a pod template.
  • Its controller loop compares matching pods with the desired count and creates or deletes pods to close the gap, whatever caused it.
  • ownerReferences link pods to their ReplicaSet for garbage collection and prevent two controllers from claiming the same pod; matching bare pods are adopted.
  • Changing the template does not touch existing pods, so ReplicaSets cannot do rolling updates alone.
  • Use Deployments instead; read ReplicaSets mainly when debugging.

Next, see how Deployments build on ReplicaSets: Deployments.