Difficulty: Beginner
What is a ReplicaSet, how does it keep the right number of Pods running, and why do we usually use a Deployment instead?
A ReplicaSet is a Kubernetes controller that keeps a specified number of identical Pods running at all times. It finds its Pods through a label selector, creates new ones from its Pod template when there are too few, and deletes extras when there are too many. In practice you rarely create ReplicaSets directly; a Deployment creates and manages them for you so it can do rolling updates and rollbacks.
replicas: the desired count, for example 3.selector: which Pods it owns, for example app: cart. Supports set-based expressions (In, NotIn, Exists), which was one improvement over the older ReplicationController.template: the Pod spec used to create new Pods. Its labels must match the selector.The ReplicaSet controller in kube-controller-manager continuously compares desired and actual state:
replicas, create Pods from the template.So if a node dies and takes a Pod with it, or someone runs kubectl delete pod, a replacement appears within seconds. Each Pod it creates has an ownerReferences entry pointing at the ReplicaSet, which is also how garbage collection removes the Pods when the ReplicaSet is deleted.
A ReplicaSet does not update existing Pods when you change its template. Only newly created Pods get the new spec. A Deployment solves this by creating a new ReplicaSet for each template change and shifting replicas from the old one to the new one gradually.
| ReplicaSet | Deployment | |
|---|---|---|
| Keeps N Pods running | Yes | Yes, through ReplicaSets |
| Rolling updates | No | Yes |
| Rollback / revision history | No | Yes, keeps old ReplicaSets |
| Pause and resume rollouts | No | Yes |
| Typical direct use | Rare | Default for stateless apps |
That is why kubectl get rs on a real cluster shows names like cart-5c9d7f6b8d: the suffix is the pod-template-hash label the Deployment adds so each ReplicaSet's Pods stay distinct.
kubectl scale rs works, but on a Deployment-owned ReplicaSet it will be overridden.apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: cart
spec:
replicas: 3
selector:
matchLabels:
app: cart
template:
metadata:
labels:
app: cart # must match the selector
spec:
containers:
- name: cart
image: myorg/cart:1.0.0
The controller keeps three Pods labelled app=cart. Changing the image here would not update the existing Pods, which is why Deployments exist.
kubectl get rs
# NAME DESIRED CURRENT READY
# cart 3 3 3
kubectl delete pod -l app=cart --wait=false
kubectl get pods -l app=cart -w # new Pods appear immediately
kubectl get pod <pod-name> -o jsonpath='{.metadata.ownerReferences[0].kind}'
# ReplicaSet
Deleting Pods triggers the reconciliation loop to create replacements, and ownerReferences shows which controller owns each Pod.
ReplicaSet, Label Selector, Reconciliation Loop, Deployment, ownerReferences