Sub topic 5
Owner references and adopting existing Pods
This chapter assumes you know what a ReplicaSet is, how label selectors match Pods, and how to run kubectl get and kubectl apply. It covers how Kubernetes records which object owns a Pod, and how that record affects what a ReplicaSet counts and deletes.
Owner references
A ReplicaSet does not track its Pods in a private list. Each Pod it creates carries an ownerReferences entry in its metadata that points back to the ReplicaSet. Run this against a Pod from the web-rs ReplicaSet:
kubectl get pod -l app=web -o jsonpath='{.items[0].metadata.ownerReferences}'The output includes the owner's kind, name and uid. It also includes controller: true, which marks the owner as the managing controller. A Pod can have only one managing controller.
Owner references serve two purposes:
- Garbage collection. When you delete an owner, the garbage collector deletes its dependents. Deleting a Deployment removes its ReplicaSets, and deleting a ReplicaSet removes its Pods.
- Claiming. A controller only manages objects that match its selector and are not owned by another controller.
Adoption
The selector decides which Pods a ReplicaSet counts. Suppose web-rs wants three replicas and you create this Pod by hand:
apiVersion: v1
kind: Pod
metadata:
name: stray-web
labels:
app: web
spec:
containers:
- name: web
image: nginx:1.25The Pod has the label app: web and no controller owner. The ReplicaSet adopts it by adding an owner reference. It now sees four matching Pods, which is one more than desired, so it deletes one. The Pod it deletes may not be the one you created.
flowchart TDUse the diagram below for the decision sequence instead.
Orphaning on purpose
You can delete a ReplicaSet without deleting its Pods:
kubectl delete rs web-rs --cascade=orphan
kubectl get pods -l app=webThe Pods keep running, and their owner references are removed. If you then apply a ReplicaSet with the same selector, it adopts them instead of creating new ones. This lets you replace a controller without downtime.
Common errors
- A bare Pod disappears. Its labels matched a selector, so a ReplicaSet adopted it and then deleted it as surplus.
- Overlapping selectors. Two controllers with overlapping selectors can both match the same Pods. The first to claim a Pod becomes its owner, and the results are hard to predict. Keep selectors distinct.
- A Pod is never adopted. If it already has a controller owner, no other controller will take it. Relabeling it does not change this.
Exercise
A ReplicaSet wants 3 replicas and has 3 Pods. You create a standalone Pod whose labels match the selector and which has no owner. What happens, and why?
Show answer
The ReplicaSet adopts the Pod by adding a controller owner reference, because it matches the selector and has no controller. It then counts 4 Pods against a desired 3, so it deletes one Pod to get back to 3.