The API and the loopLesson 6 of 8
- Desired state and the reconcile loop, not reconciled
- Control plane and nodes, not reconciled
- API machinery: groups, versions and resource versions, not reconciled
- kubectl and kubeconfig, not reconciled
- Namespaces, labels and annotations, not reconciled
- Declarative management and server-side apply, not reconciled
- Owners, finalizers and garbage collection, not reconciled
- Custom resources and operators, not reconciled
Declarative management and server-side apply
kubectl apply turns a manifest into a merge against the live object. Client-side apply remembers your last manifest in an annotation; server-side apply records which manager owns each field and refuses silent overwrites.
Shows the lesson one block at a time. Arrow keys step, number keys jump to a scene, and Escape returns to the page where you were.
Most objects in a working cluster are written by more than one party. You apply a manifest; an autoscaler changes the replica count; a controller writes status; a webhook injects a sidecar; someone on call runs kubectl scale at three in the morning. kubectl apply exists to reconcile your manifest with that shared object without trampling the parts that are not yours. How well it does that depends on which of its two merge engines you use.
Reconcile, in 8 scenes
Three management styles
| Style | Example | What the cluster remembers | Good for |
|---|---|---|---|
| Imperative commands | kubectl create deployment, kubectl scale | nothing about intent | one-off changes, experiments |
| Imperative object configuration | kubectl create -f, kubectl replace -f | the object as you last sent it | small, single-writer setups |
| Declarative object configuration | kubectl apply -f dir/ | what you applied, for the next merge | everything kept in version control |
The first two tell the API server what to do. The third tells it what you want and lets kubectl, or the API server, work out the change. Each object should have one source of truth. Mix styles on the same object and each one undoes the other’s work in ways that depend on which fields you happened to touch. kubectl warns about one common mix, applying to an object that create made:
kubectl create -f web.yaml
deployment.apps/web created
kubectl apply -f web.yaml
Warning: resource deployments/web 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/web configured
Whatever the style, the API server checks field names. kubectl validates with --validate=strict by default, and server-side field validation, GA in Kubernetes 1.27, rejects unknown and duplicated fields instead of silently dropping them. A typo fails the request:
kubectl apply -f web-typo.yaml
Error from server (BadRequest): error when creating "web-typo.yaml": Deployment in version "v1" cannot be handled as a Deployment: strict decoding error: unknown field "spec.replica"
--validate=warn turns the rejection into a warning and drops the field; --validate=false drops it without a word.
Manifestweb-typo.yaml
- deployment.apps/web
The preview runs once this page's cluster starts.$ kubectl diff -f web-typo.yamlApply also never deletes an object because its file left the directory. Remove objects with kubectl delete -f on the file you are retiring. kubectl apply --prune exists, but it deletes every object that matches its selector and is missing from the files, so a careless selector deletes far more than you meant.
Client-side apply
Plain kubectl apply is client-side apply. Every apply writes a full copy of your manifest into the kubectl.kubernetes.io/last-applied-configuration annotation, and the next apply uses it in a three-way mergeA merge that compares three versions of an object: the configuration applied last time, the configuration being applied, and the live object.:
- A field in the file is set to the file’s value.
- A field in the last-applied copy but missing from the file is deleted from the live object.
- A field in neither, because a controller, a default or another person set it, is left alone.
kubectl computes the patch on your machine and sends it as a strategic merge patch for built-in kinds, or a JSON merge patch for custom resources. Here an imperative kubectl scale changes a field that the file also sets, kubectl diff previews the merge, and apply puts the file’s value back:
kubectl apply -f web.yaml
deployment.apps/web created
kubectl scale deployment web --replicas=5
deployment.apps/web scaled
kubectl diff -f web.yaml
diff -u -N /tmp/LIVE-7215291221/apps.v1.Deployment.default.web /tmp/MERGED-7267904082/apps.v1.Deployment.default.web
--- /tmp/LIVE-7215291221/apps.v1.Deployment.default.web 2026-11-19 09:00:30.000000000 +0000
+++ /tmp/MERGED-7267904082/apps.v1.Deployment.default.web 2026-11-19 09:00:30.000000000 +0000
@@ -15,7 +15,7 @@
uid: 85694271-5cb3-4bab-9fc4-fc111ace4711
spec:
progressDeadlineSeconds: 600
- replicas: 5
+ replicas: 3
revisionHistoryLimit: 10
selector:
matchLabels:kubectl apply -f web.yaml
deployment.apps/web configured
kubectl rollout status deployment/web
Waiting for deployment "web" rollout to finish: 0 of 3 updated replicas are available... deployment "web" successfully rolled out
kubectl get deployment web
NAME READY UP-TO-DATE AVAILABLE AGE web 3/3 3 3 5s
kubectl diff runs the apply as a server-side dry run and prints live against merged. It exits with status 1 when it finds differences, so a CI job can use it to detect drift.
The second rule surprises people. Remove a field from a manifest you applied before, and apply deletes it from the live object; if the field has a default, the API server fills the default back in:
kubectl apply -f web.yaml
deployment.apps/web created
kubectl rollout status deployment/web
Waiting for deployment "web" rollout to finish: 0 of 3 updated replicas are available... deployment "web" successfully rolled out
kubectl get deployment web
NAME READY UP-TO-DATE AVAILABLE AGE web 3/3 3 3 5s
kubectl apply -f web-no-replicas.yaml
deployment.apps/web configured
kubectl rollout status deployment/web
deployment "web" successfully rolled out
kubectl get deployment web
NAME READY UP-TO-DATE AVAILABLE AGE web 1/1 1 1 5s
Client-side apply has structural limits. The annotation is a full copy of the manifest, and all of an object’s annotations together must stay under 256 KiB, so large ConfigMaps and CustomResourceDefinitions fail with metadata.annotations: Too long. The merge logic lives in kubectl, so other clients neither see nor respect it. And the annotation remembers only the last applier’s view: it knows nothing about who else changed the object.
Server-side apply
kubectl apply --server-side sends the manifest itself, as an apply patch, and the API server performs the merge. Instead of one annotation, the server tracks ownership per field. Each writer is a field managerThe name a client gives when it writes an object. Server-side apply records, per manager, the set of fields that manager last set., and the record lives in metadata.managedFields. The server-side apply reference in the Kubernetes documentation shows one on a ConfigMap:
apiVersion: v1
kind: ConfigMap
metadata:
name: test-cm
namespace: default
labels:
test-label: test
managedFields:
- manager: kubectl
operation: Apply
apiVersion: v1
time: "2010-10-10T0:00:00Z"
fieldsType: FieldsV1
fieldsV1:
f:metadata:
f:labels:
f:test-label: {}
f:data:
f:key: {}
data:
key: some value
Read fieldsV1 as a tree of field paths: f: prefixes a field name, and list items appear as k: (by key) or v: (by value). operation: Apply means the manager used server-side apply; Update means an ordinary write such as kubectl scale, kubectl edit or a controller updating status. kubectl hides this block by default; kubectl get deployment web -o yaml --show-managed-fields shows it.
Common managers:
kubectlis the default name forkubectl apply --server-side. Pass--field-managerto choose another, and keep it stable in a CI pipeline so its ownership stays in one entry.kubectl-client-side-applyrecords the fields that client-side apply wrote.- Controllers write under their own names; status written by built-in controllers usually belongs to
kube-controller-manager.
An apply states your intent for exactly the fields it contains. You own what you send. When you stop sending a field, you release it, and if no other manager owns it the API server deletes it or resets it to its default. Lists and maps merge according to markers in the schema: a list can be atomic (replaced whole), a set, or a map keyed by fields. Built-in types carry these markers, which is why the containers list merges by name. Custom resources declare them with x-kubernetes-list-type and x-kubernetes-list-map-keys.
Switching an existing object from client-side to server-side apply is a matter of adding --server-side. Ownership of the fields recorded in the last-applied annotation transfers to the kubectl manager without conflict, and kubectl keeps the annotation current, so you can go back. Fields that another command changed since your last apply, such as replicas after a kubectl scale, are not in that inheritance and raise conflicts.
Conflicts
A conflictA server-side apply request that would change a field whose value another manager set. The API server rejects it and names the manager and the field paths. stops you from silently overwriting someone else’s decision. kubectl prints the conflicting manager and paths, such as .spec.replicas, and the request changes nothing. You then choose:
- Take the field. Re-run with
--force-conflicts. Your value wins, and the field is removed from every other manager’s entry. - Give the field up. Delete it from your manifest and apply again. The other manager keeps it.
- Share it. Set your manifest to the current live value. Both managers then own the field, and it survives until every co-owner stops sending it.
Controllers should force, because they are the authority for the fields they manage. People and pipelines usually should not: a conflict is the API server telling you that someone else’s automation set that value on purpose.
Ownership clashes in practice
The classic clash is a HorizontalPodAutoscaler and a manifest that both set spec.replicas. With the field in your file, every apply moves the replica count back to the file’s value, and the autoscaler moves it again: the pods flap.
The fix is to remove replicas from the manifest once the autoscaler owns it, and the order matters:
- Client-side apply. Deleting the line deletes the field and drops the Deployment to 1 replica, as shown above, until the autoscaler catches up. Remove
spec.replicasfrom the annotation first withkubectl apply edit-last-applied deployment/web, then delete it from the file. Later applies leave the field alone. - Server-side apply. Leave
replicasin the file until the autoscaler writes the field; your next apply then reports a conflict on.spec.replicas, which is your cue to delete the line. To hand over sooner, apply a manifest containing onlyreplicasunder a private manager name such ashandover-to-hpa, then remove the field from your main manifest; the temporary manager disappears once the autoscaler writes a value of its own.
The pattern is general. A VerticalPodAutoscaler writing requests, a GitOps controller applying the same object, and a mutating webhook adding a sidecar all write fields of objects you also apply. Decide who owns each field, and leave it out of everyone else’s configuration.
Patch types
kubectl patch changes part of an object without a full manifest, in one of three formats:
| Type | Flag | Lists | Use it for |
|---|---|---|---|
| Strategic merge | default, --type=strategic | merged by the key the type declares, such as name for containers | built-in kinds: add a container, an env var, a port |
| JSON merge (RFC 7386) | --type=merge | replaced whole; null deletes a key | custom resources, simple map changes |
| JSON patch (RFC 6902) | --type=json | addressed by index | precise edits: remove one finalizer, replace one image, test a value first |
The same change shows the difference. A merge patch sends a one-element containers list, which replaces the whole list with a container that has no image, and the API server rejects it. The strategic merge patch merges into the container named web. The JSON patch addresses one field by path:
kubectl apply -f web.yaml
deployment.apps/web created
kubectl patch deployment web --type=merge -p '{"spec":{"template":{"spec":{"containers":[{"name":"web","env":[{"name":"LOG_LEVEL","value":"debug"}]}]}}}}'
The Deployment "web" is invalid: spec.template.spec.containers[0].image: Required value
kubectl patch deployment web -p '{"spec":{"template":{"spec":{"containers":[{"name":"web","env":[{"name":"LOG_LEVEL","value":"debug"}]}]}}}}'
deployment.apps/web patched
kubectl patch deployment web --type=json -p '[{"op":"replace","path":"/spec/template/spec/containers/0/image","value":"nginx:1.31"}]'
deployment.apps/web patched
kubectl get deployment web -o jsonpath='{.spec.template.spec.containers[0].image} {.spec.template.spec.containers[0].env}'
nginx:1.31 [{"name":"LOG_LEVEL","value":"debug"}]Custom resources have no strategic merge metadata, so kubectl patch on them needs --type=merge or --type=json. A patch is an imperative change: if the field is also in a manifest you apply, the next apply decides whether it survives.
kustomize
kustomizeA template-free tool, built into kubectl, that builds manifests by layering patches and generated objects on top of plain YAML. takes a directory with a kustomization.yaml and renders it. kubectl runs it with -k: kubectl kustomize dir prints the result, kubectl diff -k dir previews it, and kubectl apply -k dir applies it. The usual layout is a base and one overlay per environment:
web/
├── base/
│ ├── deployment.yaml
│ ├── service.yaml
│ └── kustomization.yaml
└── overlays/
├── staging/
│ └── kustomization.yaml
└── prod/
├── kustomization.yaml
└── replicas.yaml
# overlays/prod/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- ../../base
namespace: shop
labels:
- pairs:
app.kubernetes.io/part-of: shop
images:
- name: nginx
newTag: "1.31"
patches:
- path: replicas.yaml
configMapGenerator:
- name: web-config
literals:
- LOG_LEVEL=info
The base holds plain manifests and a kustomization that lists them under resources. The overlay pulls the base in, sets the namespace, adds labels, pins the image tag, and applies replicas.yaml, a partial Deployment merged as a strategic merge patch. configMapGenerator creates a ConfigMap whose name ends in a hash of its contents and rewrites references to it, so a configuration change produces a different name and the Deployment rolls out.
Readable output
YAML 1.1 parsers type plain scalars by guessing: no, off and n can become false, and a version like 1.20 becomes the number 1.2. KYAML is a strict subset of YAML for Kubernetes that removes the guessing. Every string value is double-quoted, and maps and lists use flow style with braces and brackets, so indentation does not carry meaning. Because it is still YAML, every YAML parser reads it. kubectl get -o kyaml prints it, GA in kubectl 1.37. The Kubernetes documentation shows a pod in KYAML:
---
{
apiVersion: "v1",
kind: "Pod",
metadata: {
name: "my-pod",
labels: {
app: "demo"
},
},
spec: {
containers: [{
name: "nginx",
image: "nginx:1.20"
}]
}
}
The image tag 1.20 survives as a string, and a country code of NO in a label would too.
mkdir -p kx-web/base kx-web/overlays/prodkubectl --context kind-kx create deployment web --image=nginx:1.30 --replicas=2 --dry-run=client -o yaml > kx-web/base/deployment.yamlprintf 'resources:\n - deployment.yaml\n' > kx-web/base/kustomization.yamlprintf 'resources:\n - ../../base\nnamePrefix: prod-\nimages:\n - name: nginx\n newTag: "1.31"\n' > kx-web/overlays/prod/kustomization.yamlkubectl --context kind-kx kustomize kx-web/overlays/prodkubectl --context kind-kx apply -k kx-web/overlays/prod --server-sidekubectl --context kind-kx scale deployment prod-web --replicas=4kubectl --context kind-kx get deployment prod-web -o yaml --show-managed-fieldskubectl --context kind-kx apply -k kx-web/overlays/prod --server-sidekubectl --context kind-kx get deployment prod-web -o kyamlkubectl --context kind-kx delete -k kx-web/overlays/prod
For your own kind cluster kx: copy a command and paste it into your terminal. Run in the simulator runs the same command in this page's simulated cluster instead; nothing on this page touches your machine. After the scale, managedFields shows replicas under the manager that scaled it, and the second server-side apply reports a conflict on .spec.replicas. Decide whether to force it or drop replicas from the base.
Actual state
Check your understanding
Your first answer to each check is the one that counts. After a miss you can answer again; passing every check reconciles the lesson.
Lesson not yet reconciled
Desired: 4 objectives, 0 metReconciled: 4 of 4 objectives met
- Explain how kubectl apply computes a change, client-side and server-side. (not yet met)
- Read managedFields and say which manager owns which field. (not yet met)
- Resolve a server-side apply conflict by forcing ownership or dropping the field from your manifest. (not yet met)
- Apply kustomize overlays with kubectl apply -k. (not yet met)
Pass every check above to reconcile this lesson.
Every check has passed, so the desired state is met. First-try accuracy: 0 of 5. This lesson's review cards are in your queue.
Practice
Put this lesson to work on the simulated cluster. Everything runs in your browser, with nothing to install.
Sources
Checked against kubernetes.io documentation for Kubernetes 1.37 on .
- kubernetes.io/docs/concepts/overview/working-with-objects/object-management
- kubernetes.io/docs/tasks/manage-kubernetes-objects/declarative-config
- kubernetes.io/docs/reference/using-api/server-side-apply
- kubernetes.io/docs/tasks/manage-kubernetes-objects/update-api-object-kubectl-patch
- kubernetes.io/docs/tasks/manage-kubernetes-objects/kustomization
- kubernetes.io/docs/concepts/workloads/autoscaling/horizontal-pod-autoscale
- kubernetes.io/docs/reference/encodings/kyaml
- kubernetes.io/docs/reference/kubectl/generated/kubectl_apply
Declarative management and server-side apply
↓ ↑ step, 1 to 8 scene, Esc leave