Sub topic 4
Watching a ReplicaSet replace deleted Pods
This chapter assumes you can read YAML, run kubectl get, describe and apply, and know that a Pod is the smallest unit Kubernetes schedules. You will create a ReplicaSet, delete a Pod, and watch the controller replace it.
What you are testing
A ReplicaSet compares the number of Pods that match its selector with spec.replicas. When the two differ, it creates or deletes Pods until they match. Deleting a Pod by hand is the simplest way to create a difference and see this loop work.
Create the ReplicaSet
Save this manifest as web-rs.yaml. The selector must match the labels in the Pod template, or the API server rejects the object.
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: 80Apply it and list the Pods:
kubectl apply -f web-rs.yaml
kubectl get pods -l app=webYou should see three Pods named web-rs- followed by a random suffix.
Delete a Pod and watch
Open two terminals. In the first, watch the Pods:
kubectl get pods -l app=web --watchIn the second, delete one Pod. Replace the name with one from your own list:
kubectl delete pod web-rs-abcdeThe watch shows the deleted Pod moving to Terminating. A new Pod with a different name appears almost at once, goes through Pending and ContainerCreating, and reaches Running. The replacement starts as soon as the old Pod is marked for deletion, so it does not wait for the old Pod to finish shutting down.
Inspect what happened
The ReplicaSet records its actions as events:
kubectl describe rs web-rsLook at the Events section. You will find a SuccessfulCreate entry for each Pod it created, including the replacement.
Pods the controller does not recognize as its own
The controller counts by label, not by name. This has two consequences you can test:
- If you remove the
app=weblabel from one Pod withkubectl label pod web-rs-abcde app-, the Pod no longer matches the selector. The ReplicaSet sees two matches and creates a new Pod. The relabeled Pod keeps running as an orphan. - If you start an extra Pod that carries
app=web, the ReplicaSet sees four matches and deletes one to get back to three.
Clean up
kubectl delete rs web-rsDeleting the ReplicaSet also deletes its Pods by default.
Exercise
You run kubectl label pod web-rs-abcde app- on one of three Pods managed by a ReplicaSet with replicas: 3. How many Pods with the label app=web exist afterward, and what happens to the relabeled Pod?
Show answer
Three Pods carry app=web. The relabeled Pod no longer matches the selector, so the ReplicaSet counts two, creates a new Pod to reach three, and leaves the relabeled Pod running outside its control.