Skip to content
LF Cert Trainer

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

1/10kubectl apply
0:00 / 4:19

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 create works once. Run it again and you get Error from server (AlreadyExists).
  • kubectl replace sends 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

One command, three possible outcomes-fweb.yamlwhat you wantkubectl applyreads the live objectNot foundcreate: createdFound, differspatch: configuredFound, identicalno write: unchanged
One command, three possible outcomes. kubectl apply first reads the object from the cluster. What it does next depends on what it finds, and the word at the end of the output line tells you which path it took.

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:

OutputWhat apply foundWhat it sent
deployment.apps/web createdNo such objectA create request, with the last applied annotation added
deployment.apps/web configuredThe object exists and the file changes somethingOne patch with only the differences
deployment.apps/web unchangedThe object exists and the file changes nothingNothing 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:

FormReads
kubectl apply -f web.yamlOne 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.yamlA 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

The three versions kubectl apply comparesStored in the clusterto setto deletecurrentPATCHsavesLocal fileweb.yaml, editedLast appliedannotation, old fileLive objectwhat the API has nowkubectl applythree-way diffAPI servervalidates the patchetcdnew live object
The three versions kubectl apply compares. The local file says what to set. The last applied configuration, an annotation stored on the object itself, says what you set before, which is the only way kubectl can tell that you removed something. The live object supplies the current values.

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:

  1. Fields to delete: everything that is in the last applied configuration but no longer in the file.
  2. Fields to set: everything in the file whose value differs from the live object, or is missing there.
  3. The annotation itself: updated to the new content of the file.

Each field therefore lands in one of four cases:

In the fileIn last appliedIn the live objectWhat apply does
YeseitherYes, other valueSets the live value to the file's value
YeseitherNoAdds the field
NoYeseitherDeletes the field from the live object
NoNoYesLeaves 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.

FieldFile nowLast appliedLiveAfter applyWhy
imagenginx:1.29nginx:1.28nginx:1.28nginx:1.29In the file, differs from live
minReadySecondsabsent55removed (back to the default, 0)You applied it before and took it out
replicas3353In the file, differs from live: the manual scale is undone
label ownerabsentabsentalicealiceNever applied by you, so not yours to delete
strategyabsentabsentRollingUpdateRollingUpdateA 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, volumes and volumeMounts are matched by name, and container ports by containerPort. 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, command and tolerations, 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.

Server-side apply: every field has an ownerimage, labelsreplicasstatusconflictYoukubectl applyAutoscalersets replicasControllerswrite statusDeployment webmanagedFieldsSecond applieralso sets replicas
Server-side apply: every field has an owner. With server-side apply the API server records which manager set each field, in metadata.managedFields. Applying a different value to a field that someone else owns is refused with a conflict instead of silently overwriting it.

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 conflict and 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 changekubectlThe API server
Memory of your last applyThe last-applied-configuration annotationmetadata.managedFields
Two writers set the same fieldThe last one silently winsConflict, unless you force it
Very large objectsCan fail: the annotation doubles the object and annotations are limited to 262144 bytesWorks: there is no annotation
Custom resourcesLists replaced as a wholeLists merged as the CRD's schema declares
Output lineconfiguredserverside-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 diff before 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 --prune flag 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.spec shows 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. Use kubectl apply --server-side -f, or kubectl create -f for 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 -f creates an object that is missing and patches one that exists; the output says created, configured or unchanged.
  • 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 diff first, --dry-run=server to check a file, and kubectl replace --force -f when 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.