Home / Technology / Kubectl Demystified: Mastering the `kubectl apply` Command

Kubectl Demystified: Mastering the `kubectl apply` Command

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:

  1. Live Object Configuration: The current state of the resource in the cluster.
  2. Last Applied Configuration: The state stored in the last-applied-configuration annotation.
  3. 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?

  1. Initial Deployment: Creating resources for the first time.
  2. Updating Resources: Modifying existing resources (e.g., scaling replicas, updating container images).
  3. GitOps/CI/CD Pipelines: Syncing cluster state with version-controlled manifests.
  4. 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

  1. 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
  1. Apply the configuration:
   kubectl apply -f deployment.yaml

Output:

   deployment.apps/nginx-deployment created
  1. Verify the Deployment:
   kubectl get deployments
   kubectl describe deployment nginx-deployment

Example 2: Updating the Deployment

  1. Modify deployment.yaml to use nginx:1.21 and scale to 3 replicas:
   spec:
     replicas: 3 # Changed from 2
     template:
       spec:
         containers:
         - name: nginx
           image: nginx:1.21 # Updated image
  1. Reapply the configuration:
   kubectl apply -f deployment.yaml

Output:

   deployment.apps/nginx-deployment configured
  1. Check the rollout status:
   kubectl rollout status deployment/nginx-deployment

Example 3: Deleting a Resource with apply

To delete a resource declaratively:

  1. Remove the resource from your YAML file.
  2. 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

  1. Always Use Declarative Commands: The CKA exam emphasizes declarative workflows. Use apply instead of create or replace.
  2. Keep Manifests Version-Controlled: Ensure YAML files are stored in Git for traceability.
  3. Avoid Manual Edits: Changes made via kubectl edit or imperative commands may conflict with apply. Stick to one method.
  4. Test with --dry-run: Validate configurations before applying.
  5. Label Resources: Use meaningful labels for easier management (e.g., app: nginx).

Troubleshooting Common Issues

  • Error: invalid configuration: Validate YAML syntax with kubectl 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

Image description

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!