The kubectl apply
command is one of the most essential tools in Kubernetes for managing resources declaratively. Whether you’re a beginner learning Kubernetes or preparing for the Certified Kubernetes Administrator (CKA) exam, understanding kubectl apply
is critical. This guide explains what the command does, when to use it, and provides practical examples to solidify your knowledge.
What is kubectl apply
?
kubectl apply
is a declarative management command used to create or update Kubernetes resources (e.g., Pods, Deployments, Services) based on configuration files written in YAML or JSON. Instead of instructing Kubernetes how to make changes (imperative approach), you declare the desired state of your resources, and Kubernetes reconciles the actual state to match.
Key Characteristics:
- Declarative: Focuses on the end state rather than the process.
- Idempotent: Safe to run multiple times (creates resources if they don’t exist; updates them if they do).
-
Change Tracking: Uses the
kubectl.kubernetes.io/last-applied-configuration
annotation to track the last applied configuration for future updates.
How Does kubectl apply
Work?
When you run kubectl apply
, Kubernetes performs a three-way merge:
- Live Object Configuration: The current state of the resource in the cluster.
-
Last Applied Configuration: The state stored in the
last-applied-configuration
annotation. - New Configuration: The YAML/JSON file you’re applying.
Kubernetes calculates differences between these states and applies only necessary changes, minimizing disruptions.
When to Use kubectl apply
?
- Initial Deployment: Creating resources for the first time.
- Updating Resources: Modifying existing resources (e.g., scaling replicas, updating container images).
- GitOps/CI/CD Pipelines: Syncing cluster state with version-controlled manifests.
- Managing Multiple Resources: Applying entire directories or Kustomize configurations.
apply
vs. create
vs. replace
-
create
: Imperative command to create new resources (fails if the resource exists). -
replace
: Overwrites an existing resource (imperative; may cause downtime). -
apply
: Declaratively creates or updates resources (safer for updates).
Examples with Step-by-Step Explanations
Example 1: Creating a Simple Deployment
-
Create a
deployment.yaml
file:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.19
- Apply the configuration:
kubectl apply -f deployment.yaml
Output:
deployment.apps/nginx-deployment created
- Verify the Deployment:
kubectl get deployments
kubectl describe deployment nginx-deployment
Example 2: Updating the Deployment
-
Modify
deployment.yaml
to usenginx:1.21
and scale to 3 replicas:
spec:
replicas: 3 # Changed from 2
template:
spec:
containers:
- name: nginx
image: nginx:1.21 # Updated image
- Reapply the configuration:
kubectl apply -f deployment.yaml
Output:
deployment.apps/nginx-deployment configured
- Check the rollout status:
kubectl rollout status deployment/nginx-deployment
Example 3: Deleting a Resource with apply
To delete a resource declaratively:
- Remove the resource from your YAML file.
- Apply the updated file:
kubectl apply -f deployment.yaml # Resource no longer exists in the file
Kubernetes detects the absence and deletes the resource (if it was previously managed by apply
).
Advanced Usage
Apply Multiple Files or Directories
kubectl apply -f deployment.yaml -f service.yaml # Multiple files
kubectl apply -f ./manifests/ # All files in a directory
Use Kustomize for Overlays
kubectl apply -k ./overlays/production/ # Applies Kustomize configuration
Dry-Run and Diff
- Simulate changes without applying:
kubectl apply -f deployment.yaml --dry-run=client
- See differences between local and live configuration:
kubectl diff -f deployment.yaml
Best Practices for CKA Exam and Real-World Use
-
Always Use Declarative Commands: The CKA exam emphasizes declarative workflows. Use
apply
instead ofcreate
orreplace
. - Keep Manifests Version-Controlled: Ensure YAML files are stored in Git for traceability.
-
Avoid Manual Edits: Changes made via
kubectl edit
or imperative commands may conflict withapply
. Stick to one method. -
Test with
--dry-run
: Validate configurations before applying. -
Label Resources: Use meaningful labels for easier management (e.g.,
app: nginx
).
Troubleshooting Common Issues
-
Error:
invalid configuration
: Validate YAML syntax withkubectl apply --validate=true
. - Conflict During Update: Resolve by reapplying the corrected manifest.
- Unexpected Deletions: Ensure resources are removed from YAML files intentionally.
Summary Table: kubectl apply
vs. Related Commands
Command | Approach | Use Case | Idempotent? |
---|---|---|---|
apply |
Declarative | Create/update resources | Yes |
create |
Imperative | Create new resources | No |
replace |
Imperative | Overwrite existing resources | No |
Final Thoughts
Mastering kubectl apply
is foundational for Kubernetes administrators. By declaring your desired state and letting Kubernetes handle the rest, you ensure consistent, repeatable deployments. For the CKA exam, practice applying configurations, updating resources, and troubleshooting with dry-run and diff. With this knowledge, you’re well on your way to Kubernetes proficiency! 🚀
Pro Tip: Set up a practice cluster (e.g., using Minikube) and experiment with kubectl apply
to build muscle memory. Happy Kubernetting!