Lesson 23 · Section 2: Core Concepts
Lesson 23: Imperative vs declarative: two ways to tell Kubernetes what you want
Give orders step by step, or describe the result and let kubectl work out the steps. How each style works underneath, what breaks when you mix them, and which one wins you time in the exam. · 20 min read · 5 min video
Official competencies this lesson covers
Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.
Why there are two styles
Every change you make to a cluster ends up as a request to the API server. What differs is how much of the thinking you do yourself.
Think of a taxi. You can give directions: turn left, go straight for two streets, stop here. That works, but only if you know exactly where the car is right now, and afterwards nobody can tell where you meant to go. Or you can give the address. The driver works out the route from wherever the car happens to be, and you can hand the same address to any driver on any day.
- Imperative is the directions. You tell Kubernetes which operation to perform: create this, scale that, delete this. You are responsible for knowing the current state and for choosing the right next step.
- Declarative is the address. You write down what should exist, in a file, and
kubectl applycompares it with the cluster and performs whatever operations are needed: create, change or nothing at all.
What the two styles are
Parts:
- You (know what you want)
- Commands (run, create, scale)
- web.yaml (the result you want)
- kubectl apply (finds the difference)
- API server (validates, stores)
- Deployment web (the live object)
Connections:
- You to Commands: say each step
- You to web.yaml: describe the result
- web.yaml to kubectl apply: -f
- Commands to API server: one change each
- kubectl apply to API server: only what differs
- API server to Deployment web
The Kubernetes documentation splits this into three techniques, and the middle one is the one that confuses people:
| Technique | Typical commands | You keep | Who chooses the operation |
|---|---|---|---|
| Imperative commands | kubectl run, create deployment, expose, scale, set image, edit, label, delete | Nothing: the cluster is the only record | You |
| Imperative object configuration | kubectl create -f, replace -f, delete -f | A file per object | You |
| Declarative object configuration | kubectl apply -f, kubectl diff -f | Files or whole directories | kubectl, per object |
Notice that a YAML file does not make you declarative; the verb does. kubectl create -f web.yaml is still an
order ("create this"), and it fails if web already exists. kubectl apply -f web.yaml is a statement ("this should
exist, like this"), and it succeeds whether web is missing, outdated or already correct.
That last property has a name: idempotent. Running the same apply twice gives the same result as running it
once, which is what makes it safe in scripts, pipelines and GitOps tools.
kubectl create -f web.yaml # second run: Error from server (AlreadyExists)
kubectl apply -f web.yaml # second run: deployment.apps/web unchanged
How it works underneath
Kubernetes itself is always declarative
Parts:
- Desired state (spec: replicas 3)
- Controller (compares, then acts)
- Actual state (status: 2 running)
- Create 1 Pod (closes the gap)
Connections:
- Desired state to Controller: wants
- Actual state to Controller: has
- Controller to Create 1 Pod: acts
- Create 1 Pod to Actual state: now 3
Here is the part the comparison tables leave out. The choice between imperative and declarative is only about how
you talk to the API server. Inside the cluster there is only one model: every object has a spec (what you want)
and a status (what exists), and controllers work in a loop to make the second match the first.
kubectl scale deployment web --replicas=5 does not start two Pods. It changes one number, spec.replicas, and
returns. The Deployment controller, the ReplicaSet controller, the scheduler and the kubelet then notice the gap and
close it. That is also why Kubernetes heals itself: if a Pod dies, nobody has to give a new order, because the desired
state still says five.
So an imperative command is a quick way to edit desired state. A declarative file is a way to own desired state: keep it, review it, version it and apply it again.
Under the hood · What each kubectl verb sends to the API server
| You type | kubectl sends | If the object exists | If it does not exist |
|---|---|---|---|
kubectl create ... or create -f | POST (create) | Fails: AlreadyExists | Creates it |
kubectl replace -f | PUT (update the whole object) | Overwrites it with the file | Fails: NotFound |
kubectl apply -f | GET, then PATCH or POST | Patches only what differs | Creates it |
kubectl scale, set image, label, edit | A change to a few fields | Changes those fields | Fails: NotFound |
kubectl delete | DELETE | Deletes it | Fails: NotFound (unless --ignore-not-found) |
replace and apply look similar and are not. replace sends the whole object as it is in your file, so
anything that is in the live object but not in the file is dropped, including changes made by other people or tools.
apply sends a patch, so everything it does not mention survives.
How kubectl apply decides what to change
Parts:
- Your file (what you want now)
- last-applied (what you asked before)
- Live object (what the cluster has)
- kubectl apply (compares all three)
- Patch (set these, clear those)
- API server (merges the patch)
Connections:
- Your file to kubectl apply: set
- last-applied to kubectl apply: what to clear
- Live object to kubectl apply: compare
- kubectl apply to Patch
- Patch to API server: PATCH
To be able to send only the difference, kubectl apply needs to know what you asked for last time. It stores a copy
of your file on the object itself, in the annotation kubectl.kubernetes.io/last-applied-configuration. On every run
it compares three things:
- Your file: what you want now.
- The last-applied annotation: what you asked for last time.
- The live object: what the cluster has, including defaults and fields set by controllers.
From them it works out a patch with two simple rules:
- Set every field in the file whose value differs from the live object.
- Clear every field that is in last-applied but no longer in the file: you removed it, so it should go.
Anything else is left alone. A field that is only in the live object (a default, a status, an annotation added by a
controller, a replica count managed by an autoscaler) was never yours, so apply does not touch it.
You can read the stored copy at any time:
kubectl apply view-last-applied deployment/web
Under the hood · Server-side apply: the same idea, tracked per field
The annotation approach is called client-side apply, because kubectl does the comparison. Its weakness is that it only remembers what kubectl apply did. It does not know that someone else scaled the Deployment, so it can silently overwrite their change.
Server-side apply (kubectl apply --server-side) moves the merge into the API server. Instead of one annotation,
the server records an owner for every field in metadata.managedFields: each writer is a field manager. If you
apply a different value for a field that another manager owns, you get a conflict error instead of a silent
overwrite. You then decide: change your file to match, drop the field from your file, or take the field over with
--force-conflicts.
kubectl apply --server-side -f web.yaml
kubectl get deployment web --show-managed-fields -o yaml # who owns which field
Client-side apply is still kubectl's default and is all you need for the exam, but controllers and GitOps tools increasingly use server-side apply.
When to use which
| Imperative commands | Imperative with files | Declarative (apply) | |
|---|---|---|---|
| Speed for a single small change | Fastest | Slow | Medium |
| Record of what you intended | None | The file | The file |
| Review and version control | No | Yes | Yes |
| Safe to run again | No (create fails) | No | Yes |
| Keeps changes made by others | Yes (touches few fields) | No: replace overwrites | Yes |
| Works on a whole directory | No | One verb for all files | Yes, mixed create and update |
| Every field available | No, only what flags offer | Yes | Yes |
| Best for | Exam tasks, experiments, quick fixes | Recreating an object from a saved file | Real clusters, teams, automation |
In production the answer is almost always declarative: files in Git, applied by a pipeline. In the exam the answer is "whatever is fastest and correct", which usually means imperative commands for simple objects and generated YAML for the rest.
- apply file: replicas 3
- scale by hand to 5
- file still says 3
- next apply: back to 3
Using it
Example · Imperative: create, change and expose a Deployment in four commands
Run nginx with three replicas, scale it, roll out a newer image and make it reachable inside the cluster.
kubectl create deployment web --image=nginx:1.28 --replicas=3
kubectl scale deployment web --replicas=5
kubectl set image deployment/web nginx=nginx:1.29 # container name = image name by default
kubectl expose deployment web --port=80
Fast, and nothing to clean up. But nothing records what you did either: to rebuild web on another cluster you would
have to remember all four commands, in order.
Example · Declarative: the same Deployment as a file
Describe the result once:
# web.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
replicas: 3
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: nginx
image: nginx:1.28
kubectl apply -f web.yaml # deployment.apps/web created
kubectl apply -f web.yaml # deployment.apps/web unchanged
To change it, edit the file, look at what would change, then apply:
sed -i 's/nginx:1.28/nginx:1.29/' web.yaml
kubectl diff -f web.yaml # shows the image line with - and +
kubectl apply -f web.yaml # deployment.apps/web configured
apply takes a directory too: kubectl apply -f manifests/ creates what is missing and updates what changed, and
-R goes into sub-directories.
Example · The exam hybrid: let a command write the file
Task: a Deployment api with two replicas of nginx:1.29, where each container requests 100m of CPU. No imperative
flag sets resource requests on create deployment, so generate the manifest and add them.
kubectl create deployment api --image=nginx:1.29 --replicas=2 --dry-run=client -o yaml > api.yaml
--dry-run=client builds the object without sending it, and -o yaml prints it. Open api.yaml, find the empty
resources: {} and fill it in:
resources:
requests:
cpu: 100m
kubectl apply -f api.yaml
kubectl get deployment api -o jsonpath='{.spec.template.spec.containers[0].resources}'
You typed four lines of YAML instead of twenty, and the selector and labels cannot be wrong.
Example · Change something that cannot be changed in place
Most fields of a running Pod are immutable. If a task asks you to change one (a command, a volume, an environment
variable), neither edit nor apply can do it. Save the Pod, fix the file, and replace it:
kubectl get pod worker -o yaml > worker.yaml
vim worker.yaml # make the change
kubectl replace --force -f worker.yaml # deletes the Pod, then creates it from the file
replace --force is imperative on purpose: it says "delete and create", which is exactly what an immutable field
needs. For Pods owned by a Deployment, change the Deployment instead and let it roll out new Pods.
Tricks
Common mistakes
- Running
kubectl createtwice. The second run fails withAlreadyExists. If you are fixing a file and trying again, usekubectl apply -f, orkubectl replace --force -fwhen the fix touches an immutable field. - Editing the cluster, then applying the old file.
kubectl editandkubectl scaledo not update your YAML. The nextapplyreverts every field the file names. Change the file first, then apply. - Using
replacewhereapplywas meant.replaceoverwrites the whole object from the file and fails if the object is missing. It also drops fields that others set, such as replicas managed by an autoscaler. applyon an object made withcreate. It works, but kubectl warns that the last-applied annotation is missing and adds it. From then on removing a field from the file clears it; fields removed before that point stay. To avoid the warning, create withkubectl create --save-configor simply useapplyfrom the start.- Expecting a deleted file to delete the object.
applyonly looks at the files you give it. Removingweb.yamlfrom a directory leaveswebrunning: delete it withkubectl delete -f web.yamlbefore removing the file, orkubectl delete deployment webafter. - Setting
replicasin a file when an autoscaler owns it. Everyapplyresets the count. Leavereplicasout of the manifest andapplywill keep whatever the autoscaler chose.
Recap
- Imperative = you give the steps (
run,create,scale,set,edit). Declarative = you describe the result in a file andkubectl applyworks out the steps. - A file is not enough:
create -fandreplace -fare still imperative. Onlyapplyis declarative. - Inside the cluster everything is declarative: controllers move actual state toward
spec, whatever you typed. applycompares your file, the last-applied annotation and the live object, and patches only the difference.- In the exam: imperative for one-liners,
--dry-run=client -o yamlplusapplyfor the rest, and never let a hand-made change and a file disagree.
Official docs
Quiz: check what you learned
5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.
Sign in to take the quiz and keep your score.
Practise: try it on a real cluster
2 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.
Create and expose an application fast, write a manifest without creating anything, and change a running Deployment.
Build · Level 1 · warm-up · target 10 min
Change four live objects with kubectl patch and its relatives: clear a finalizer, remove one container, add one setting without losing the others, and edit a custom resource.
Fix · Level 2 · standard · target 20 min
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.