Sub topic 3
ReplicaSets: keeping N Pods running
This chapter assumes you can read YAML, use kubectl get, describe and apply, and know that a Pod is the smallest unit Kubernetes schedules. It also assumes you know that labels are key/value pairs attached to objects.
What a ReplicaSet does
A ReplicaSet is a controller that keeps a stated number of identical Pods running. You declare the count in spec.replicas. The ReplicaSet controller compares that number with the Pods it can find, then creates or deletes Pods until the two match. This comparison runs continuously, so it also corrects drift such as a deleted Pod or a failed node.
The three parts of the spec
A ReplicaSet needs three things:
replicas: how many Pods you want.selector: a label query that decides which Pods count toward that number.template: the Pod definition used to create new Pods.
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: web-rs
spec:
replicas: 3
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: web
image: nginx:1.25
ports:
- containerPort: 80The selector must match the labels in the template. If it does not, the API server rejects the object. Otherwise the ReplicaSet would create Pods that it could never count.
How the control loop works
The count only includes Pods that match the selector and are not being deleted. The controller never inspects the image or the container settings of an existing Pod. It looks only at labels and the count.
Try it
kubectl apply -f replicaset.yaml
kubectl get rs web-rs
kubectl get pods -l app=webkubectl get rs shows DESIRED, CURRENT and READY columns. DESIRED is spec.replicas. CURRENT is the number of Pods the ReplicaSet owns. READY is how many of them pass their readiness check.
Delete one Pod with kubectl delete pod <name> and list Pods again. A replacement appears within seconds, with a new name.
Common errors
- Selector too broad. If an unrelated Pod carries
app: web, the ReplicaSet counts it. It may adopt that Pod if it has no other controller, and it may later delete it when scaling down. - Editing the template and expecting a change. Changing
templateaffects only Pods created afterwards. Existing Pods keep their old image. Managing this is the reason Deployments exist. - Mismatched selector and labels. The object is rejected with a validation error.
Exercise
A ReplicaSet has replicas: 3 and selector app=web. You manually create a fourth Pod with the label app=web and no other owner. What does the ReplicaSet do?
Show answer
It counts the fourth Pod toward its total, finds four where it wants three, and deletes one Pod. It may delete the one you created, because the controller does not distinguish Pods by origin once they match the selector.