Skip to content
LF Cert Trainer

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

1/12Imperative vs declarative
0:00 / 4:44

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 apply compares it with the cluster and performs whatever operations are needed: create, change or nothing at all.

What the two styles are

Two ways to reach the same objectsay each stepdescribe the result-fone change eachonly what differsYouknow what you wantCommandsrun, create, scaleweb.yamlthe result you wantkubectl applyfinds the differenceAPI servervalidates, storesDeployment webthe live object
Two ways to reach the same object. Imperative: you say each step and kubectl sends it. Declarative: you describe the result in a file and kubectl works out which steps are needed. Both end as the same object in the API server.

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:

TechniqueTypical commandsYou keepWho chooses the operation
Imperative commandskubectl run, create deployment, expose, scale, set image, edit, label, deleteNothing: the cluster is the only recordYou
Imperative object configurationkubectl create -f, replace -f, delete -fA file per objectYou
Declarative object configurationkubectl apply -f, kubectl diff -fFiles or whole directorieskubectl, 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

Inside the cluster, everything is declarativewantshasactsnow 3Desired statespec: replicas 3Controllercompares, then actsActual statestatus: 2 runningCreate 1 Podcloses the gap
Inside the cluster, everything is declarative. Whatever you typed, the API server only stores what you want (spec). A controller keeps comparing it with what exists (status) and acts until they match.

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 typekubectl sendsIf the object existsIf it does not exist
kubectl create ... or create -fPOST (create)Fails: AlreadyExistsCreates it
kubectl replace -fPUT (update the whole object)Overwrites it with the fileFails: NotFound
kubectl apply -fGET, then PATCH or POSTPatches only what differsCreates it
kubectl scale, set image, label, editA change to a few fieldsChanges those fieldsFails: NotFound
kubectl deleteDELETEDeletes itFails: 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

How kubectl apply decides what to changesetwhat to clearcomparePATCHYour filewhat you want nowlast-appliedwhat you asked beforeLive objectwhat the cluster haskubectl applycompares all threePatchset these, clear thoseAPI servermerges the patch
How kubectl apply decides what to change. kubectl apply compares three things: your file, the copy of your previous file stored on the object, and the live object. It sends only the differences, so fields that others own are left alone.

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:

  1. Your file: what you want now.
  2. The last-applied annotation: what you asked for last time.
  3. 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 commandsImperative with filesDeclarative (apply)
Speed for a single small changeFastestSlowMedium
Record of what you intendedNoneThe fileThe file
Review and version controlNoYesYes
Safe to run againNo (create fails)NoYes
Keeps changes made by othersYes (touches few fields)No: replace overwritesYes
Works on a whole directoryNoOne verb for all filesYes, mixed create and update
Every field availableNo, only what flags offerYesYes
Best forExam tasks, experiments, quick fixesRecreating an object from a saved fileReal 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.

  1. apply file: replicas 3
  2. scale by hand to 5
  3. file still says 3
  4. next apply: back to 3
How a manual change gets lost

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 create twice. The second run fails with AlreadyExists. If you are fixing a file and trying again, use kubectl apply -f, or kubectl replace --force -f when the fix touches an immutable field.
  • Editing the cluster, then applying the old file. kubectl edit and kubectl scale do not update your YAML. The next apply reverts every field the file names. Change the file first, then apply.
  • Using replace where apply was meant. replace overwrites 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.
  • apply on an object made with create. 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 with kubectl create --save-config or simply use apply from the start.
  • Expecting a deleted file to delete the object. apply only looks at the files you give it. Removing web.yaml from a directory leaves web running: delete it with kubectl delete -f web.yaml before removing the file, or kubectl delete deployment web after.
  • Setting replicas in a file when an autoscaler owns it. Every apply resets the count. Leave replicas out of the manifest and apply will keep whatever the autoscaler chose.

Recap

  • Imperative = you give the steps (run, create, scale, set, edit). Declarative = you describe the result in a file and kubectl apply works out the steps.
  • A file is not enough: create -f and replace -f are still imperative. Only apply is declarative.
  • Inside the cluster everything is declarative: controllers move actual state toward spec, whatever you typed.
  • apply compares 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 yaml plus apply for 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.