0
0
Kubernetesdevops~5 mins

kubectl apply vs create in Kubernetes - CLI Comparison

Choose your learning style9 modes available
Introduction
When managing applications on Kubernetes, you often need to add or update resources like pods or deployments. The commands kubectl create and kubectl apply help you do this, but they work differently. Understanding when to use each helps keep your cluster organized and up to date.
When you want to add a new resource to your cluster for the first time, like a new pod or service.
When you want to update an existing resource's configuration without deleting it first.
When you have a configuration file and want Kubernetes to track changes over time.
When you want to quickly create a resource without managing updates later.
When you want to automate updates in a safe way that merges changes.
Config File - pod.yaml
pod.yaml
apiVersion: v1
kind: Pod
metadata:
  name: example-pod
spec:
  containers:
  - name: nginx-container
    image: nginx:1.23
    ports:
    - containerPort: 80

This YAML file defines a simple Pod named example-pod running an Nginx container version 1.23. The apiVersion and kind specify the resource type. metadata sets the pod's name. spec describes the container details.

Commands
This command creates the pod defined in pod.yaml for the first time. It will fail if the pod already exists.
Terminal
kubectl create -f pod.yaml
Expected OutputExpected
pod/example-pod created
-f - Specifies the file containing the resource definition
This command lists all pods in the current namespace to verify that example-pod is running.
Terminal
kubectl get pods
Expected OutputExpected
NAME READY STATUS RESTARTS AGE example-pod 1/1 Running 0 10s
This command creates the pod if it doesn't exist or updates it if it does, applying changes from pod.yaml.
Terminal
kubectl apply -f pod.yaml
Expected OutputExpected
pod/example-pod configured
-f - Specifies the file containing the resource definition
Check the pod status again to confirm the apply command worked and the pod is running.
Terminal
kubectl get pods
Expected OutputExpected
NAME READY STATUS RESTARTS AGE example-pod 1/1 Running 0 20s
Key Concept

If you remember nothing else from this pattern, remember: use kubectl create to add new resources once, and kubectl apply to create or update resources safely over time.

Common Mistakes
Using kubectl create to update an existing resource
kubectl create will fail if the resource already exists, causing errors.
Use kubectl apply to update existing resources without errors.
Using kubectl apply without a configuration file
kubectl apply needs a file to know what to create or update; without it, the command fails.
Always provide a valid resource definition file with -f flag.
Summary
kubectl create adds a new resource and fails if it already exists.
kubectl apply creates or updates a resource, merging changes safely.
Use kubectl get pods to verify the resource status after creation or update.