ReplicaSets
A ReplicaSet keeps a fixed number of identical Pods running. You give it three things:
replicas: how many Pods you want,- a
selector: which Pods count as "mine", - a Pod
template: what to create when there are too few.
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: web
spec:
replicas: 3
selector:
matchLabels:
app: web
template: # a Pod manifest without apiVersion/kind
metadata:
labels:
app: web # must satisfy the selector
spec:
containers:
- name: nginx
image: nginx:1.27In practice you almost never create ReplicaSets yourself: a Deployment creates and manages them for you (next lesson). Understanding them explains everything a Deployment does.
The reconcile loop
The ReplicaSet controller repeats one simple calculation:
diff = len(matching, non-terminating Pods) - spec.replicas
diff < 0 -> create |diff| Pods from the template
diff > 0 -> delete diff Pods (preferring the "least valuable" ones)
diff == 0 -> nothing to doHere is that loop as a runnable model. We start empty, survive a deleted Pod, then scale up and down:
import itertools
counter = itertools.count(1)
pods = []
def reconcile(rs):
mine = [p for p in pods if p["labels"].get("app") == rs["selector"]["app"]]
diff = len(mine) - rs["replicas"]
if diff < 0:
for _ in range(-diff):
pod = {"name": f"{rs['name']}-{next(counter):03d}", "labels": dict(rs["template_labels"])}
pods.append(pod)
print(" create", pod["name"])
elif diff > 0:
for pod in mine[-diff:]: # newest first, for simplicity
pods.remove(pod)
print(" delete", pod["name"])
names = [p["name"] for p in pods if p["labels"].get("app") == rs["selector"]["app"]]
print(f" -> {len(names)}/{rs['replicas']}: {names}")
rs = {"name": "web", "replicas": 3, "selector": {"app": "web"}, "template_labels": {"app": "web"}}
print("initial:"); reconcile(rs)
pods.pop(1)
print("a Pod was deleted:"); reconcile(rs)
rs["replicas"] = 5
print("scaled to 5:"); reconcile(rs)
rs["replicas"] = 2
print("scaled to 2:"); reconcile(rs)initial:
create web-001
create web-002
create web-003
-> 3/3: ['web-001', 'web-002', 'web-003']
a Pod was deleted:
create web-004
-> 3/3: ['web-001', 'web-003', 'web-004']
scaled to 5:
create web-005
create web-006
-> 5/5: ['web-001', 'web-003', 'web-004', 'web-005', 'web-006']
scaled to 2:
delete web-004
delete web-005
delete web-006
-> 2/2: ['web-001', 'web-003']
Which Pods are deleted when scaling down?
The real controller doesn't pick randomly. It ranks candidates and deletes from the top of this list:
- Pods not yet scheduled to a node,
- Pods that are
PendingbeforeRunning, - Pods that aren't Ready before Ready ones,
- Pods on nodes with more replicas of this ReplicaSet (spreading the survivors),
- more recently created (younger) Pods before older ones.
(You can also influence it with the controller.kubernetes.io/pod-deletion-cost annotation.)
pods = [
{"name": "web-a", "node": "n1", "phase": "Running", "ready": True, "age": 300},
{"name": "web-b", "node": "n1", "phase": "Running", "ready": True, "age": 120},
{"name": "web-c", "node": "n2", "phase": "Running", "ready": True, "age": 500},
{"name": "web-d", "node": "n1", "phase": "Running", "ready": False, "age": 60},
{"name": "web-e", "node": None, "phase": "Pending", "ready": False, "age": 5},
]
per_node = {}
for p in pods:
per_node[p["node"]] = per_node.get(p["node"], 0) + 1
def deletion_rank(p):
return (
p["node"] is not None, # unscheduled first
p["phase"] == "Running", # pending before running
p["ready"], # not-ready before ready
-per_node[p["node"]], # crowded nodes first
p["age"], # younger first
)
order = sorted(pods, key=deletion_rank)
print("deletion order:", [p["name"] for p in order])
print("scale 5 -> 2 deletes:", [p["name"] for p in order[:3]])deletion order: ['web-e', 'web-d', 'web-b', 'web-a', 'web-c']
scale 5 -> 2 deletes: ['web-e', 'web-d', 'web-b']
Ownership and orphans
When a ReplicaSet creates a Pod, it sets metadata.ownerReferences on it. That link powers garbage collection: delete the ReplicaSet and its Pods are deleted too.
kubectl get pod web-001 -o jsonpath='{.metadata.ownerReferences[0].kind}/{.metadata.ownerReferences[0].name}'
kubectl delete rs web # Pods are garbage-collected
kubectl delete rs web --cascade=orphan # keep the Pods running, unownedWarning: A ReplicaSet adopts any Pod whose labels match its selector, even one you created by hand. If you start a bare Pod with
app: webnext to a ReplicaSet wanting 3, the controller sees 4 and deletes one.
ReplicaSet vs ReplicationController
The older ReplicationController does the same job with equality-only selectors. It is legacy: use Deployments (which use ReplicaSets).
Test yourself
A ReplicaSet wants 3 Pods and sees 5 matching Pods. What does it do?
- Creates 3 more
- Deletes 2
- Does nothing
- Deletes all and recreates 3
When scaling down, which Pod does the controller prefer to delete first?
- The oldest Ready Pod
- An unscheduled, Pending Pod
- The Pod with the most restarts
- A random Pod
Which field links a Pod to the ReplicaSet that created it?
- metadata.labels
- metadata.ownerReferences
- spec.nodeName
- status.phase