Lesson 25 · Section 2: Core Concepts
Lesson 25: kubectl apply: how Kubernetes merges your file into a live object
What kubectl apply really does: the three versions of an object it compares, why some fields are removed and others survive, server-side apply, and the habits that make it safe and fast in the exam. · 20 min read · 4 min video
Official competency this lesson covers
Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.
Why kubectl apply exists
The first two commands most people learn for manifests are kubectl create -f and kubectl replace -f. Both break
down as soon as an object has a life of its own:
kubectl createworks once. Run it again and you getError from server (AlreadyExists).kubectl replacesends your file as the whole object. Anything that is not in the file is reset: the replica count the autoscaler chose, a label a teammate added, an annotation a controller relies on.
A live object is shared. You wrote part of it, the API server filled in defaults, controllers write the status, an
autoscaler may own the replica count, and other people patch it. What you need is a command that says "make my
fields look like this file, and leave the rest alone", and that you can run any number of times with the same
result. That command is kubectl apply.
What apply does
Parts:
- web.yaml (what you want)
- kubectl apply (reads the live object)
- Not found (create: created)
- Found, differs (patch: configured)
- Found, identical (no write: unchanged)
Connections:
- web.yaml to kubectl apply: -f
- kubectl apply to Not found
- kubectl apply to Found, differs
- kubectl apply to Found, identical
For every object in the file, kubectl apply reads the object with the same kind, name and namespace from the
cluster, then takes one of three paths. The last word of the output line tells you which:
| Output | What apply found | What it sent |
|---|---|---|
deployment.apps/web created | No such object | A create request, with the last applied annotation added |
deployment.apps/web configured | The object exists and the file changes something | One patch with only the differences |
deployment.apps/web unchanged | The object exists and the file changes nothing | Nothing at all |
Because the outcome depends only on the file and the current state, apply is idempotent: running it twice is the same as running it once. That is what makes it the declarative command: you describe the result, and you never have to remember whether the object is already there.
-f is flexible about where the manifest comes from:
| Form | Reads |
|---|---|
kubectl apply -f web.yaml | One file, which may hold several objects separated by --- |
kubectl apply -f manifests/ | Every .yaml, .yml and .json file in the folder (add -R for subfolders) |
kubectl apply -f https://example.com/install.yaml | A manifest downloaded from a URL, the usual way to install a network plugin |
kubectl apply -f - | Standard input, so you can pipe or paste a manifest |
kubectl apply -k overlays/prod/ | The output of a Kustomize folder instead of plain files |
How it works: the three-way merge
Parts:
- Local file (web.yaml, edited)
- Last applied (annotation, old file), in Stored in the cluster
- Live object (what the API has now), in Stored in the cluster
- kubectl apply (three-way diff)
- API server (validates the patch)
- etcd (new live object)
Connections:
- Local file to kubectl apply: to set
- Last applied to kubectl apply: to delete
- Live object to kubectl apply: current
- kubectl apply to API server: PATCH
- API server to etcd: saves
If apply only compared your file with the live object, it could never delete anything. A field that is in the live object but not in your file might be a default, something a controller added, or something you set last week and have now removed on purpose. The file and the live object alone cannot tell those apart.
So every time apply writes an object, it also saves a copy of the file's content on the object, as JSON, in the
annotation kubectl.kubernetes.io/last-applied-configuration. The next apply then has three versions to compare:
- The local file: what you want now.
- The last applied configuration: what you wanted last time.
- The live object: what exists, including everything other writers added.
From those it builds one patch in three steps:
- Fields to delete: everything that is in the last applied configuration but no longer in the file.
- Fields to set: everything in the file whose value differs from the live object, or is missing there.
- The annotation itself: updated to the new content of the file.
Each field therefore lands in one of four cases:
| In the file | In last applied | In the live object | What apply does |
|---|---|---|---|
| Yes | either | Yes, other value | Sets the live value to the file's value |
| Yes | either | No | Adds the field |
| No | Yes | either | Deletes the field from the live object |
| No | No | Yes | Leaves it alone |
A worked example makes it concrete. You applied a Deployment with replicas: 3, minReadySeconds: 5 and the image
nginx:1.28. Since then someone ran kubectl scale --replicas=5 and kubectl label deployment web owner=alice. Now
you edit the file: the image becomes nginx:1.29 and you delete the minReadySeconds line.
| Field | File now | Last applied | Live | After apply | Why |
|---|---|---|---|---|---|
image | nginx:1.29 | nginx:1.28 | nginx:1.28 | nginx:1.29 | In the file, differs from live |
minReadySeconds | absent | 5 | 5 | removed (back to the default, 0) | You applied it before and took it out |
replicas | 3 | 3 | 5 | 3 | In the file, differs from live: the manual scale is undone |
label owner | absent | absent | alice | alice | Never applied by you, so not yours to delete |
strategy | absent | absent | RollingUpdate | RollingUpdate | A default, never applied by you |
The replicas row surprises people: apply does not "respect" the manual scale. If a field is in your file, the file
wins every time.
Under the hood · How lists are merged, and why custom resources behave differently
For built-in kinds, apply sends a strategic merge patch. It knows from the API definitions how each list should be treated:
- Lists with a merge key are merged item by item.
containers,env,volumesandvolumeMountsare matched byname, and containerportsbycontainerPort. You can add one container to the file without disturbing a sidecar that an admission webhook injected into the live Pod template. - Lists without a merge key, such as
args,commandandtolerations, are replaced as a whole. - The order of merged lists is not guaranteed to follow your file.
Custom resources carry no merge keys, so client-side apply falls back to a plain JSON merge patch for them, in which every list is replaced as a whole. Server-side apply (below) fixes this, because CRD authors can declare list types in the schema.
To delete a field that you never applied, set it to null in the file. Apply clears fields that are explicitly null
even when the last applied configuration does not mention them.
Client-side and server-side apply
Everything so far is client-side apply: kubectl does the comparison and sends a patch. Since Kubernetes 1.22 there is a stable second mode, server-side apply, where kubectl sends the file as it is and the API server does the merge.
Parts:
- You (kubectl apply)
- Autoscaler (sets replicas)
- Controllers (write status)
- Deployment web (managedFields)
- Second applier (also sets replicas)
Connections:
- You to Deployment web: image, labels
- Autoscaler to Deployment web: replicas
- Controllers to Deployment web: status
- Second applier to Deployment web: conflict
Instead of one annotation, the API server keeps a record of who set which field in metadata.managedFields.
Every writer has a manager name: kubectl for server-side apply, kubectl-client-side-apply for the classic mode,
kube-controller-manager for the built-in controllers, and so on. When you apply:
- Fields you send become yours.
- Fields you sent last time and have now left out are removed, if nobody else owns them. This is the same deletion rule as before, without needing the annotation.
- A field that another manager owns, with a different value from yours, is a conflict. The request fails with
Apply failed with 1 conflictand names the manager and the field. You then choose: drop the field from your file and let the other manager keep it, or take it over with--force-conflicts.
| Client-side apply (default) | Server-side apply (--server-side) | |
|---|---|---|
| Who computes the change | kubectl | The API server |
| Memory of your last apply | The last-applied-configuration annotation | metadata.managedFields |
| Two writers set the same field | The last one silently wins | Conflict, unless you force it |
| Very large objects | Can fail: the annotation doubles the object and annotations are limited to 262144 bytes | Works: there is no annotation |
| Custom resources | Lists replaced as a whole | Lists merged as the CRD's schema declares |
| Output line | configured | serverside-applied |
Plain kubectl apply is still client-side by default, and it is all you need for most exam tasks. Know that the
other mode exists, what a conflict means, and that --server-side is the fix when a huge manifest is rejected with
metadata.annotations: Too long.
Under the hood · Looking at field ownership
kubectl get hides managedFields because it is long. Ask for it when you want to know who set a field:
kubectl -n shop get deployment web -o yaml --show-managed-fields
Each entry lists a manager, an operation (Apply for server-side apply, Update for everything else) and the
fields it owns in fieldsV1. An object that was first managed with client-side apply can be moved over simply by
running kubectl apply --server-side -f on the same file: kubectl uses the old annotation to hand ownership over
without conflicts, as long as the annotation is still accurate.
Using it
Example · Create, change and roll out a Deployment from one file
Keep the manifest in a file and let apply work out what to do each time.
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
namespace: shop
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
# edit web.yaml: image nginx:1.29
kubectl diff -f web.yaml # shows the image change
kubectl apply -f web.yaml # deployment.apps/web configured
kubectl -n shop rollout status deployment web
The second apply sends nothing. The third changes the Pod template, so the Deployment starts a rolling update, and
kubectl rollout undo can take it back. A change outside the Pod template, such as replicas, is applied without a
rollout.
Example · Adopt an object that was created imperatively
A task gives you a running Deployment api that somebody created with kubectl create deployment, and asks for a
change that has no quick imperative command, such as adding a volume. Export it, edit it, apply it:
kubectl -n shop get deployment api -o yaml > api.yaml
# edit api.yaml: add the volume and the volumeMount; you may delete the status: block
kubectl apply -f api.yaml
Warning: resource deployments/api is missing the kubectl.kubernetes.io/last-applied-configuration
annotation which is required by kubectl apply. kubectl apply should only be used on resources created
declaratively by either kubectl create --save-config or kubectl apply. The missing annotation will be
patched automatically.
deployment.apps/api configured
The warning is harmless here: with no last applied configuration, apply cannot delete anything on this first run, so
it only sets what your file changes, and it writes the annotation for next time. Leaving status in the exported
file is harmless too, because writes to the main resource ignore it. Do delete the resourceVersion line if you keep
the file for later: it pins the file to one version of the object, and a later apply fails with "the object has been
modified" once anything else has changed the object.
Example · A field that cannot be changed in place
You are asked to change the command of a running Pod, or the selector of a Deployment. Apply reports that the API server refused the patch:
The Pod "probe" is invalid: spec: Forbidden: pod updates may not change fields other than
`spec.containers[*].image`, ...
The Deployment "web" is invalid: spec.selector: Invalid value: ...: field is immutable
Apply cannot patch an immutable field, so the object has to be deleted and created again. One command does both from your edited file:
kubectl replace --force -f probe.yaml # delete, then create
For a bare Pod that is the normal way to change it. For a Deployment, remember that this deletes its Pods too, so there is no rolling update.
Tricks
Common mistakes
- Expecting apply to keep a manual change. If the field is in the file, the file wins.
kubectl diffbefore the apply shows that a manual scale or image change is about to be undone. - Expecting apply to delete an object. Removing a manifest from a folder removes nothing from the cluster; apply
only looks at the objects it is given. Delete with
kubectl delete -f old.yaml. The--pruneflag exists for this, but it is still alpha and can delete more than you meant, so stay away from it in the exam. - A typo in a field name. Current versions reject it:
strict decoding error: unknown field "spec.replica". Read the path in the message, fix the indentation or the name, and apply again.kubectl explain deployment.specshows the right names. - The wrong namespace. Apply uses the namespace in the file's metadata, or else your current one. If the file
names a namespace and you pass a different one with
-n, apply stops with "the namespace from the provided object does not match". If the file names none, the object quietly lands wherever your context points. - Applying a huge manifest. Large CRD bundles can be rejected with
metadata.annotations: Too long, because the saved copy does not fit in an annotation. Usekubectl apply --server-side -f, orkubectl create -ffor a first install. - Treating the missing annotation warning as an error. It is a warning, and the line after it tells you the apply went through.
Recap
kubectl apply -fcreates an object that is missing and patches one that exists; the output sayscreated,configuredorunchanged.- The patch comes from three versions: the local file, the live object and the last applied configuration stored in an annotation.
- Fields in the file are set, fields you removed from the file are deleted, and fields you never applied are kept.
- Server-side apply (
--server-side) moves the merge into the API server, tracks an owner per field and reports conflicts. - In the exam:
kubectl difffirst,--dry-run=serverto check a file, andkubectl replace --force -fwhen a field is immutable.
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.
Release a change with kubectl apply, remove a setting through the file, and bring a hand-made Deployment under apply.
Build · Level 2 · standard · target 15 min
Section capstone. Take over a half-finished namespace: get its Deployment running under a Pod limit, repair its Service, open it on a node port, add a Pod that calls another namespace, and write it all down as a manifest.
Fix · Level 3 · challenge · target 30 min
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.