kubectl apply -- Declarative Resource Management
kubectl apply is the cornerstone of declarative Kubernetes management. Instead of telling Kubernetes what to do step by step, you describe the desired state in a file and let Kubernetes figure out how to get there.
How apply Works
When you run kubectl apply -f, Kubernetes compares the file you provide against the current state of the resource in the cluster. It then makes only the changes necessary to match your desired state.
# Apply a single file
kubectl apply -f deployment.yaml
# Apply all files in a directory
kubectl apply -f ./manifests/
# Apply from a URL
kubectl apply -f https://example.com/deployment.yaml
apply vs create
The key difference is what happens when the resource already exists:
# create fails if the resource already exists
kubectl create deployment my-app --image=nginx
kubectl create deployment my-app --image=nginx # ERROR: already exists
# apply creates the resource if it does not exist, or updates it if it does
kubectl apply -f deployment.yaml # creates the resource
kubectl apply -f deployment.yaml # updates it (no error)
This makes apply safe to run repeatedly, which is essential for automation and CI/CD pipelines.
Field Management and Last-Applied Configuration
When you use kubectl apply, Kubernetes stores the last-applied configuration as an annotation on the resource. On subsequent applies, it uses this annotation to determine which fields were removed from your manifest versus fields managed by other tools.
# View the last-applied annotation
kubectl get deployment my-app -o jsonpath='{.metadata.annotations.kubectl\.kubernetes\.io/last-applied-configuration}' | jq .
This three-way merge considers:
- The new manifest you are applying
- The last-applied configuration
- The live state of the resource
Server-Side Apply
Starting with Kubernetes 1.22, server-side apply moves the merge logic to the API server and provides better field ownership tracking:
kubectl apply -f deployment.yaml --server-side
Server-side apply tracks which manager owns each field, preventing accidental overwrites when multiple tools manage the same resource.
Applying Recursively
Apply all manifests in nested directories:
kubectl apply -f ./manifests/ -R
Key Takeaways
kubectl applyis idempotent -- safe to run multiple times- It creates resources if they do not exist and updates them if they do
- The three-way merge uses the last-applied annotation to detect changes
- Server-side apply provides better field ownership for multi-tool environments
- Use
applyfor all production and version-controlled resources