kubectl Cheatsheet
Lookup, not reading: come back when a lab or drill needs speed. See the Learning Path.
Docs: kubectl quick reference Β· JSONPath support Β· kubectl reference
Overviewβ
The CKAD is a speed test: roughly two hours of hands-on tasks in live clusters. The winning habit is imperative first: generate YAML with kubectl create ... --dry-run=client -o yaml, edit only the fields the generator can't set, then apply. Typing manifests from memory is slow and error-prone. Search kubernetes.io/docs for the rest; it's the only site you can open during the exam. Command Patterns teaches which command fits which task; this page makes you fast at them: shell setup, output formatting, and dense command lists for the exam.
Key conceptsβ
Output formatsβ
| Flag | Gives |
|---|---|
-o wide | Extra columns: node, IP |
-o yaml / -o json | The full object |
-o name | pod/web-5c9b, ready for scripts |
-o jsonpath='{...}' | Specific fields |
-o custom-columns=NAME:.metadata.name,... | Your own table |
--show-labels, -L app | Labels as a column |
--sort-by=.metadata.creationTimestamp | Sorted rows |
kubectl essentialsβ
Shell setup, first thing in the exam (the k alias and completion are usually preconfigured; check with type k):
alias k=kubectl
source <(kubectl completion bash); complete -o default -F __start_kubectl k
export do="--dry-run=client -o yaml" # k create deploy web --image=nginx $do > web.yaml
export now="--force --grace-period=0" # k delete pod web $now
k config set-context --current --namespace=lab # stop typing -n
The exam shell is bash. In zsh, $do isn't word-split: write ${=do}.
Vim, so pasted YAML keeps its indentation (~/.vimrc):
set expandtab tabstop=2 shiftwidth=2 autoindent
In vim, :set paste before pasting from the docs, V + > / < to shift a block, :%s/old/new/g to replace.
Context and lookup:
k config get-contexts
k config use-context <ctx>
k api-resources --namespaced=true -o name | head
k explain deployment.spec.strategy.rollingUpdate
k explain pod.spec --recursive | grep -i toleration
Generate, edit, apply:
k run web --image=nginx:1.27 $do > pod.yaml
k create deployment web --image=nginx:1.27 --replicas=3 $do > deploy.yaml
k apply -f deploy.yaml
k replace --force -f pod.yaml # recreate a Pod after editing an immutable field
k diff -f deploy.yaml # preview what apply would change
Rollouts:
k set image deployment/web nginx=nginx:1.28
k rollout status deployment/web
k rollout history deployment/web
k rollout undo deployment/web --to-revision=1
k rollout restart deployment/web
k scale deployment/web --replicas=5
Labels, selectors and annotations:
k label pod web tier=frontend
k label pod web tier- # remove a label
k annotate deployment web owner=team-a
k get pods -l 'app=web,tier!=backend'
k get pods -l 'env in (prod,staging)'
k get pods --field-selector status.phase!=Running -A
Debugging:
k describe pod <pod>
k logs <pod> --previous -c <container>
k get events --sort-by=.lastTimestamp
k exec -it <pod> -- sh
k debug -it <pod> --image=busybox:1.36 --target=<container>
k run tmp --rm -it --image=busybox:1.36 --restart=Never -- wget -qO- -T 3 http://web
k top pods --sort-by=memory
JSONPath and custom columns:
k get pods -o jsonpath='{.items[*].metadata.name}'
k get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.podIP}{"\n"}{end}'
k get pod web -o jsonpath='{.spec.containers[*].image}'
k get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")].address}'
k get pods -o custom-columns='NAME:.metadata.name,NODE:.spec.nodeName,IMAGE:.spec.containers[0].image'
k get pods -A -o jsonpath='{.items[*].spec.containers[*].image}' | tr ' ' '\n' | sort | uniq -c
k get secret db -o jsonpath='{.data.password}' | base64 -d
π§ͺ Labβ
Requires: Standard lab setup Β· the k alias Β· How the tiers work.
Speed drill: eight tasks in ten minutes.
Goal
Work in namespace lab8-1. Only imperative commands and $do + a quick edit are allowed.
- Pod
nginx(nginx:1.27) with labeltier=web. - Deployment
api(nginx:1.27, 3 replicas), exposed as ClusterIP Serviceapion 80. - ConfigMap
cfgwithMODE=prod, injected intoapias env vars. - Scale
apito 5, then update its image tonginx:1.28, then roll back. - Job
once(busybox:1.36) that runsecho done. - CronJob
tickevery 5 minutes runningdate. - Print each Pod's name and node, one per line.
- Print the image of every container in the namespace with a count.
Verify
k -n lab8-1 get pod nginx --show-labels
k -n lab8-1 get deploy api -o jsonpath='{.spec.replicas} {.spec.template.spec.containers[0].image}{"\n"}' # 5 nginx:1.27
k -n lab8-1 get job once -o jsonpath='{.status.succeeded}{"\n"}' # 1
k -n lab8-1 get cronjob tick
π‘ Hints
1β6. Each one is a row in Command Patterns β I want toβ¦. Set the namespace once with set-context to save typing -n.
7. -o custom-columns= with .metadata.name and .spec.nodeName.
8. jsonpath over .items[*].spec.containers[*].image, then tr, sort and uniq -c.
π’ Guided
-
Create the namespace and make it the default for every command below.
k create namespace lab8-1 && k config set-context --current --namespace=lab8-1 -
A Pod with a label.
k run nginx --image=nginx:1.27 --labels=tier=web -
A Deployment with 3 replicas.
k create deployment api --image=nginx:1.27 --replicas=3 --port=80 -
A ClusterIP Service in front of it.
k expose deployment api --port=80 -
A ConfigMap with one key.
k create configmap cfg --from-literal=MODE=prod -
Inject it into the Deployment as env vars.
k set env deployment/api --from=configmap/cfg -
Scale to 5.
k scale deployment api --replicas=5 -
Ship a new image.
k set image deployment/api nginx=nginx:1.28 -
Roll it back.
k rollout undo deployment/api -
A one-off Job.
k create job once --image=busybox:1.36 -- echo donek wait --for=condition=complete job/once --timeout=60s -
A CronJob every 5 minutes.
k create cronjob tick --image=busybox:1.36 --schedule="*/5 * * * *" -- date -
One line per Pod: name and node.
k get pods -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName -
Every container image, counted.
k get pods -o jsonpath='{.items[*].spec.containers[*].image}' | tr ' ' '\n' | sort | uniq -c -
Run the β Check below, then switch the default back and delete everything the lab created.
k config set-context --current --namespace=default && k delete namespace lab8-1
β Check
t() { [ "$2" = "$3" ] && echo "PASS $1" || echo "FAIL $1: got '$2', want '$3'"; }
t "nginx labelled" "$(kubectl -n lab8-1 get pod nginx -o jsonpath='{.metadata.labels.tier}')" "web"
t "api: 5 on 1.27" "$(kubectl -n lab8-1 get deploy api -o jsonpath='{.spec.replicas} {.spec.template.spec.containers[0].image}')" "5 nginx:1.27"
t "api reads cfg" "$(kubectl -n lab8-1 get deploy api -o jsonpath='{.spec.template.spec.containers[0].env[0].valueFrom.configMapKeyRef.name}')" "cfg"
t "Service api on 80" "$(kubectl -n lab8-1 get svc api -o jsonpath='{.spec.ports[0].port}')" "80"
t "Job once succeeded" "$(kubectl -n lab8-1 get job once -o jsonpath='{.status.succeeded}')" "1"
t "CronJob tick" "$(kubectl -n lab8-1 get cronjob tick -o jsonpath='{.spec.schedule}')" "*/5 * * * *"
Gotchasβ
--dry-run=clientvalidates nothing against the server. A typo'd field passes.--dry-run=serverruns full validation and admission.kubectl applyon an object made withcreateprints alast-applied-configurationwarning. Harmless, but mixing both styles makes diffs confusing.- Invalid
kubectl editsaves are kept in/tmp. The error message gives the path.kubectl apply -fit after fixing. --force --grace-period=0hides problems. Fine for exam speed; in production it skips graceful shutdown and can leave the old Pod running on an unreachable node.kubectl run -- cmdsets args, not the command. β See What--does.- Quote selectors, jsonpath and custom-columns.
!=,(),{}and[*]mean something to the shell. - Namespace on every command. After
set-context --namespace, remember to switch back, or later tasks land in the wrong place.
Scenario questionsβ
Q1 β
Find every Pod in the cluster that isn't Running, fastest way.
Model answer
- Clarify: include
SucceededJob Pods? They are finished, not broken. - Observe: phase is a field on every Pod, and field selectors filter on the server.
- Hypothesise:
kubectl get pods -A --field-selector status.phase!=Running,status.phase!=Succeeded. - Fix: then
describethe interesting ones. Note thatCrashLoopBackOffPods have phaseRunning, so also scankubectl get pods -A | grep -v Runningor sort by restarts. - Prevent: a saved alias or dashboard for this view. It's the first thing to check in any incident.
Q2 β β Produce a table of every Deployment with its image and replica count, across all namespaces.
Model answer
- Clarify: one container per Pod, or can there be several?
- Observe: the fields live at
.spec.template.spec.containers[*].imageand.spec.replicas. - Hypothesise: custom columns are clearer than jsonpath ranges.
- Fix:
kubectl get deploy -A -o custom-columns='NS:.metadata.namespace,NAME:.metadata.name,REPLICAS:.spec.replicas,IMAGE:.spec.template.spec.containers[*].image'. - Prevent: for anything more complex than a table,
-o json | jqis easier to read and debug than long jsonpath.
Q3 β
β
You need to change a field on a running Pod and kubectl edit refuses to save. What happened and what do you do?
Model answer
- Clarify: which field? Is the Pod owned by a controller?
- Observe: the error says
Pod updates may not change fields other than .... kubectl saved your edit to a file in/tmp. - Hypothesise: most Pod spec fields are immutable. Only a few (such as
image) can change in place. - Fix: standalone Pod:
kubectl replace --force -f /tmp/kubectl-edit-xxxx.yaml. Owned Pod: change the Deployment instead, which rolls out new Pods. - Prevent: in the exam, generate YAML to a file first and edit the file, not the live object.
Q4 β β β List Deployments whose containers have no CPU request, cluster-wide, for an HPA rollout.
Model answer
- Clarify: do LimitRange defaults count? They are injected into Pods, not Deployments.
- Observe: jsonpath can filter with
?(), but "field missing" filters are awkward and error-prone. - Hypothesise:
-o json | jqis the right tool:kubectl get deploy -A -o json | jq -r '.items[] | select(any(.spec.template.spec.containers[]; .resources.requests.cpu == null)) | "\(.metadata.namespace)/\(.metadata.name)"'. - Fix: add requests to those Deployments before creating HPAs, or rely on LimitRange defaults (then check Pods, not Deployments).
- Prevent: an admission policy (ValidatingAdmissionPolicy or Kyverno) that requires CPU requests. β See Resources & Scaling.
Summaryβ
- Generate, don't type.
$doand a quick edit beats writing YAML from memory. - Know which fields the generators can't set. Probes, volumes and strategy always need an edit.
--afterrunsets args; aftercreateit sets the command.- jsonpath for one field, custom-columns for a table, jq for logic.
- Set the namespace per task and set it back. Wrong-namespace work scores zero.
Next in path β Learning Path