Full lesson
Explore the full explanation, examples, and visuals at your own pace.
Part 1
kubectl diff shows what kubectl apply would change, before anything changes. It takes your file, web.yaml, and compares it with the live web Deployment, the Kubernetes object that keeps your app's pods running. Then it prints only the lines that differ. Nothing gets saved to the cluster.
Same Deployment, two versions
Here's our case. You only meant to bump the image from web:1.3 to web:1.4. But a teammate scaled the live web Deployment to 5 replicas, meaning five running copies. Your file still says 2. Running apply would quietly overwrite both fields, not just the image.
What kubectl diff does
You run kubectl diff with the file. kubectl first fetches the live web Deployment from the API server. Then it asks the API server for a dry-run apply, which is a pretend apply that saves nothing. The API server returns the would-be web, kubectl compares the two, and hands you only the changed lines. Nothing is stored.
Diff output for web.yaml
Lines starting with a minus show the live value. Lines with a plus show what apply would set. The image moving from web:1.3 to web:1.4 is the change you wanted. But replicas going from 5 to 2 is the surprise. Applying that would remove three pods your teammate added.
$ kubectl diff -f web.yaml
spec:
- replicas: 5
+ replicas: 2
template:
...
- image: web:1.3
+ image: web:1.4Preview reads, apply writes
Same file, two commands. With kubectl diff, web.yaml is compared against the live web Deployment. It only reads, so the cluster still has 5 pods. With kubectl apply, that same file gets written to live web, and you're down to 2 pods. Diff is a preview that touches nothing.
Read the diff, then decide
The image line is expected, so you keep it. The replicas line is the surprise, so you set replicas to 5 in web.yaml and rerun the diff. Now only the image line shows. Diff shows differences; you judge them.
- Expected line? Leave it
- Surprise line? Fix web.yaml first
- Rerun diff until only intended lines
Habit: diff before apply
Make it a habit. Run kubectl diff -f web.yaml first, and it changes nothing. Review the output, and fix the file if something surprises you. Then run kubectl apply -f web.yaml. On shared or production clusters, someone may have edited live objects, so this check matters most.
# 1. preview, changes nothing
kubectl diff -f web.yaml
# 2. review, fix the file if needed
# 3. apply what you just saw
kubectl apply -f web.yamlkubectl diff is a preview of apply that touches nothing.
kubectl diff is a preview of apply that touches nothing. Preview the change instead of finding out afterward, so the live web Deployment gets only the image update, web:1.4, and the replicas your teammate set stay exactly as they were.