$ cat ckad-prep/part-04.md
CKAD Prep, Part 4: Who Owns This Pod?

Where we are
Hi, I’m Reza. I’m sharing my preparation for the CKAD exam, practiced on a K3s cluster in my home lab. I am a junior engineer looking for my first SRE, DevOps or Cloud job, and that is why I learn in public. You can see how I think, what breaks, and how I fix it.
Part 3 ended with a gap: a ReplicaSet keeps the number of pods right, but a new image never reaches the running ones. Deployments fill that gap. This part is about how they do it, and who owns what:
- C1: create and scale a Deployment.
- C2: follow the ownership chain with
ownerReferences. - C4: delete a pod, then delete its ReplicaSet, and watch both come back.
- C5: fix a Deployment manifest with two bugs.
(C3, where the template changes a few times, sits between C2 and C4. I’m leaving its details out of this part, but you’ll see its leftovers in C4.)
The key picture is a chain of three levels. You only create the top one:

The confusing part: you create a Deployment, but the pods belong to a ReplicaSet that the Deployment made. So kubectl get pods api finds nothing.
C1: create and scale a Deployment
The task: a Deployment api, with nginx:1.27, 3 replicas and port 80. Then scale it to 5.
Cleanup first
kubectl delete -f 04-rs-broken.yaml
This deletes rs-broken from Part 3, and its pods with it. Why? It selects app=api, and so does the new Deployment. The two controllers wouldn’t steal each other’s pods (a pod that already has a controller can’t be adopted). But anything that reads by label would see both sets: kubectl get pods -l app=api, and later a Service, which would send traffic to the old pods too.
delete -f removes the objects the file describes. The file itself stays in the repo.
The skeleton
kubectl create deploy api --image=nginx:1.27 --replicas=3 --port=80 --dry-run=client -o yaml > 06-api-deploy.yaml
create deploymakes a Deployment (kubectl runonly makes pods). It puts the labelapp: apiin three places for you: the Deployment’s metadata, the selector, and the template.- The container is named after the image (
nginx), not after the Deployment.
The file
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
labels:
app: api
spec:
replicas: 5
selector:
matchLabels:
app: api
template:
metadata:
labels:
app: api
spec:
containers:
- name: nginx
image: nginx:1.27
ports:
- containerPort: 80
metadata.labelsare labels on the Deployment object itself. They only help you find the Deployment. Which pods it manages is the selector’s job.replicasstarted at 3, then went to 5. The Deployment passes this number on to its current ReplicaSet.- The selector is required and immutable, like the ReplicaSet’s in Part 3. The Deployment uses it to find its ReplicaSets.
- Any change under
template:makes a new ReplicaSet. That’s how a Deployment rolls out a change. Changing replicas doesn’t touch the template, so scaling reused the same ReplicaSet.
I removed the dry-run noise: creationTimestamp: null, strategy: {}, resources: {}, status: {}. strategy defaults to RollingUpdate.
Waiting and checking
kubectl apply -f 06-api-deploy.yaml
kubectl rollout status deploy/api
kubectl get deploy,rs,pods -l app=api --show-labels
rollout statuswaits until every replica is updated and available, then printssuccessfully rolled out. It exits non-zero on failure, so it works in scripts and CI. Better than runninggetagain and again.- One
getfor three types.-l app=apiapplies to all of them. READY 5/5is ready pods over desired.UP-TO-DATEis pods running the current template.AVAILABLEis pods that have been Ready for at leastminReadySeconds(0 by default).
The pod-template-hash label
The ReplicaSet is called api-7579bcc6c4. That suffix is the pod-template-hash: a hash of the pod template. The Deployment adds it as a label to the ReplicaSet and its pods, and to the ReplicaSet’s selector. So when a template change makes a second ReplicaSet, the two never overlap, even though both have app=api. It’s the built-in fix for the overlap problem I avoided by deleting rs-broken.
Pod names follow the chain: <deployment>-<template-hash>-<random>.
Two mistakes
I scaled to 6, not 5. get deploy showed 6/6. I fixed the file and applied again. This is my third “right command, wrong value” mistake in this lab, after the image tags in Part 2. The habit I need: re-read the task after each scenario, and compare every number, name and tag.
kubectl get pods api gave NotFound. api is the Deployment, not a pod. Its pods are api-<hash>-<random>. Use kubectl get pods -l app=api or kubectl get deploy api.
NAME READY UP-TO-DATE AVAILABLE AGE
api 5/5 5 5 3m43s
NAME DESIRED CURRENT READY AGE
api-7579bcc6c4 5 5 5 3m45s
Five replicas, from one ReplicaSet, because scaling doesn’t make a new one.
C2: follow the ownership chain
The task: find the ReplicaSet owned by api, and one pod owned by that ReplicaSet. Write both names to /opt/ckad/00/chain.txt. Not by reading names, but through metadata.ownerReferences, the field that records “who controls me”.
First, the whole chain as a table
kubectl get rs -o custom-columns=RS:.metadata.name,OWNER_KIND:.metadata.ownerReferences[0].kind,OWNER:.metadata.ownerReferences[0].name
kubectl get pods -o custom-columns=POD:.metadata.name,OWNER_KIND:.metadata.ownerReferences[0].kind,OWNER:.metadata.ownerReferences[0].name
ownerReferencesis a list. An object can have several owners, but only one withcontroller: true.[0]is the controller for everything in this lab..kindand.nameare the owner’s type and name. There’s also.uid, which is what Kubernetes actually matches on. Names can be reused after a delete. UIDs never are.- The
api-*pods show ReplicaSet /api-7579bcc6c4. My bare pods from Parts 1 and 2 (broken,printer,sleeper,web) show<none>. Nothing recreates them if they’re deleted.
The typo that looked like an answer
My first try showed <none> for every row, including the pods I knew had an owner. I had typed .metadata.ownerReference[0], without the s. That field doesn’t exist, and custom-columns doesn’t complain. It just prints <none>, which looks exactly like “this object has no owner”.
This is the fourth problem in this lab with the same root: jsonpath and custom-columns don’t validate field names. A wrong path prints blank or <none>. My rule now: if the output is empty or <none> and I didn’t expect that, I check the path with kubectl explain pod.metadata.ownerReferences before I believe it.
Finding the ReplicaSet with a filter
RS=$(kubectl get rs -o jsonpath='{.items[?(@.metadata.ownerReferences[0].name=="api")].metadata.name}')
.items, becauseget rswithout a name returns a List (the lesson from Part 1).[?( ... )]is a filter: keep only the items where the condition is true.@is the current item while the filter loops..metadata.nameafter the filter gives the names of the items that matched. Result:api-7579bcc6c4.- A weak spot: it matches on the owner’s name only, not its kind. Good enough here, and the check at the end confirms the kind.
Finding a pod with a filter
POD=$(kubectl get pods -o jsonpath="{.items[?(@.metadata.ownerReferences[0].name==\"$RS\")].metadata.name}" | awk '{print $1}')
- Double quotes outside this time, so bash puts in
$RSbefore kubectl sees the expression. Inside, a literal"must be written\". - The filter matches all 5 pods, printed on one line.
awk '{print $1}'keeps the first one:api-7579bcc6c4-2ttzr.
Writing the answer, and checking it from the other side
echo -e "$RS\n$POD" > /opt/ckad/00/chain.txt
kubectl get pod "$POD" -o jsonpath='{.metadata.ownerReferences[0].kind}/{.metadata.ownerReferences[0].name}{"\n"}'
-emakes echo turn\ninto a real newline, so the file has two lines.- The check reads the pod’s owner directly:
ReplicaSet/api-7579bcc6c4. That matches line 1 of the file.
I used shell variables instead of one long command, so I could check each piece with echo before the next step used it. Slower than a one-liner, but each step is verified.
C4: delete a pod, then delete the ReplicaSet
The task: test self-healing at two levels of the chain. After C3, the current ReplicaSet is api-7d54f6c494, still with 5 pods.
Level 1: delete a pod
kubectl delete pod api-7d54f6c494-2hpff
The pod’s owner still exists, and still wants 5. The ReplicaSet counts 4, and creates one from its template: api-7d54f6c494-hng7s, AGE 3s.
It’s a new pod, with a new name and a new IP. Not the old one coming back. The other 4 pods kept serving the whole time, so there was no downtime.
Level 2: delete the ReplicaSet
First I saved its UID:
RS=api-7d54f6c494
kubectl get rs $RS -o jsonpath='{.metadata.uid}{"\n"}'
The API server gives every object a unique ID when it’s created, and never reuses it. Names can repeat after a delete. UIDs can’t. That makes the UID the only reliable way to tell “the same object” from “a new object with the same name”. Before: d1fd3f3a-ca8c-4c39-9e63-064f5a22a471.
kubectl delete rs $RS
kubectl rollout status deployment/api
What happened, in order:
- The ReplicaSet is deleted. By default this is a background cascading delete: the owner goes first, then the garbage collector deletes everything whose
ownerReferencespoint at the old UID. That’s all 5 pods. - The Deployment notices it has no ReplicaSet for its current template.
- It hashes the template:
7d54f6c494, the same as before, because the template didn’t change. So the new ReplicaSet gets the same name. - The new ReplicaSet creates 5 new pods.
The UID after: 92db45f2-d624-450a-80c2-a020ba75a3f4. Different. A new object with the old name.
This is the confusing part. The ReplicaSet “came back” with an identical name, so it looks as if the delete did nothing. Only the UID and the AGE (27 seconds) show it’s new. That’s why I recorded the UID before and after: the name alone can’t prove anything.
And unlike level 1, all 5 pods were gone at the same moment. That’s downtime.
I predicted all of this before running it: same name, new UID, 5 new pods. All confirmed.
The Deployment rebuilds the current template
After C3, there were three older ReplicaSets at 0 replicas: 7579bcc6c4, 5bdd66b8cc and 7f4887bdf6. The Deployment ignored them. It rebuilt the current template, not an old revision. Going back to an old one takes an explicit kubectl rollout undo.
Who heals what
- Delete a pod: its ReplicaSet creates 1 replacement. No downtime.
- Delete the current ReplicaSet: garbage collection removes all its pods, and the Deployment makes a new ReplicaSet with all new pods. Downtime.
- Delete the Deployment: garbage collection removes its ReplicaSets, then their pods. Gone for good.
- Delete a bare pod (like
webfrom Part 1): nobody notices. It stays deleted.
Three ways to cascade
--cascade=background(the default): the owner first, then the garbage collector removes what it owned.--cascade=foreground: the owned objects first, then the owner.--cascade=orphan: delete only the owner. The owned objects keep running, with no owner.
With orphan, the 5 pods would have survived. The Deployment’s new ReplicaSet would then have adopted them, like the stray pod in Part 3, with no downtime at all.
The answer file:
1. Deleting a pod: the ReplicaSet saw 4 of 5 pods and created a replacement right away (new pod name, same ReplicaSet).
2. Deleting the ReplicaSet: its pods were garbage-collected, and the Deployment created a new ReplicaSet (same template hash name, new UID) with 5 new pods.
C5: a Deployment from a broken file
The task: a Deployment manifest called shop with two bugs. Fix it and get 2 pods running.
- Bug 1:
kind: deployment, in lowercase. - Bug 2: no
spec.selector.
The interesting part: the two bugs are caught by different checks, and you only see one error at a time.
Bug 1: the lowercase kind
kind must match the registered type name exactly, including case. To see the real error, I tested the lowercase version on its own, with a server-side dry run (nothing gets created):
Error from server (BadRequest): error when creating "STDIN": deployment in version "v1" cannot be handled as a Deployment: no kind "deployment" is registered for version "apps/v1" in scheme "k8s.io/apimachinery@v1.37.2-k3s1/..."
How to read it:
Error from server (BadRequest): kubectl accepteddeployment. Its lookup ignores case, just to find the right URL. So it sent the request, and the server rejected it.cannot be handled as a Deployment: the server knew which resource it was, from the URL…no kind "deployment" is registered: …but thekindfield in the body doesn’t match any registered name, and that check is case-sensitive.
I had predicted a different error: a client-side resource mapping not found … no matches for kind. That’s what many guides show, from older kubectl versions or for kinds that don’t exist at all. On this cluster (K3s, v1.37), it reaches the server. The outcome is the same, rejected, but the message is different. That’s why I test instead of trusting my prediction.
One honest detail: during the real task, I never saw this error. My first apply went straight to the selector error. That means I had already typed kind: Deployment correctly while writing the file. The separate test is what showed me the real message.
Bug 2: the missing selector
The Deployment "shop" is invalid:
* spec.selector: Required value
* spec.template.metadata.labels: Invalid value: {"app":"shop"}: `selector` does not match template `labels`
This is a validation error (is invalid). So the server decoded the object fine, meaning the kind was correct, and then checked its fields.
Two lines, but one cause. With no selector, nothing can match the labels, so the second line follows from the first. When several validation errors appear, look for the one the others depend on.
spec.selector is required in apps/v1. Older API versions (extensions/v1beta1) filled it in from the template labels, which is why old tutorials leave it out. The fix:
spec:
replicas: 2
selector:
matchLabels:
app: shop
template:
metadata:
labels:
app: shop
spec:
containers:
- name: shop
image: nginx:1.27
The selector is immutable, so it has to be right on the first successful apply. And app: shop matters later in the lab, when a broken Service tries to select it.
deployment.apps/shop created
deployment "shop" successfully rolled out
NAME READY UP-TO-DATE AVAILABLE AGE
shop 2/2 2 2 24s
Which layer catches which error
A manifest goes through several checks, in order. Each one stops at the first failure, so you fix, apply again, and read the next error:
kubectlparses the YAML: bad indentation or tabs.error converting YAML to JSON.kubectlmaps the resource: an unknownapiVersion, or a kind that doesn’t exist.no matches for kind.- The server decodes the body: a kind with the wrong case.
BadRequest ... no kind "x" is registered. - The server validates the fields: missing or invalid fields.
is invalid: * spec.x: .... - The cluster runs it: a bad image or a crash. You see it in the pod status, like the broken pod in Part 2.
To check a file without creating anything: kubectl apply --dry-run=server -f file.yaml. It runs every server check and stores nothing. --dry-run=client only checks what kubectl can check locally, so it would miss the case problem, and possibly the missing selector.
What I learned
- A Deployment owns ReplicaSets, and ReplicaSets own pods. You create the top, and the pods are named
<deployment>-<template-hash>-<random>. replicasscales the current ReplicaSet. A template change makes a new one. The pod-template-hash label keeps them from overlapping.rollout statuswaits for a Deployment, and fails loudly if it doesn’t finish.ownerReferencesis the real chain, and jsonpath filters ([?(@.x=="y")]) can follow it.- A wrong field name prints
<none>, not an error. Check the path withkubectl explainbefore you believe empty output. - Names can repeat. UIDs can’t. A ReplicaSet that comes back with the same name is still a new object.
- Each level heals the level below. Deleting a pod costs nothing. Deleting the current ReplicaSet takes every pod down at once.
- Manifest errors come one layer at a time. Fix, apply again, read the next one.
--dry-run=serverruns every server check without creating anything. - Re-read the task. Right command, wrong number (6 instead of 5) is still a wrong answer.
What is next
Next in the lab: more about labels and selectors, and then Services, the stable name and IP in front of pods that keep changing. The shop Deployment from C5 is waiting there for a broken Service