Cheat sheets
kubectl commands
The kubectl commands and flags that cover most CKA tasks, grouped by purpose.
Setup: alias k=kubectl, export do="--dry-run=client -o yaml", export now="--force --grace-period=0".
Create
| Object | Command |
|---|---|
| Pod | k run web --image=nginx:1.27 --port=80 --labels=a=b |
| Deployment | k create deploy web --image=nginx:1.27 --replicas=3 |
| Service | k expose deploy web --port=80 --target-port=8080 --type=NodePort |
| Job | k create job j --image=busybox:1.36 -- date |
| CronJob | k create cronjob c --image=busybox:1.36 --schedule="*/5 * * * *" -- date |
| ConfigMap | k create cm app --from-literal=K=V --from-file=f |
| Secret | k create secret generic s --from-literal=pw=x |
| ServiceAccount | k create sa ci |
| Role and binding | k create role r --verb=get,list --resource=pods then k create rolebinding rb --role=r --user=u |
| Ingress | k create ingress i --class=nginx --rule="host/path*=svc:80" |
| Quota | k create quota q --hard=pods=10,cpu=4 |
| YAML only | add $do > file.yaml |
Change
| Goal | Command |
|---|---|
| Image, env, resources | k set image deploy/web web=nginx:1.28, k set env deploy/web K=V, k set resources deploy/web --limits=cpu=1 |
| Replicas | k scale deploy/web --replicas=5 |
| Labels, annotations | k label pod p k=v --overwrite, k annotate pod p n=v, trailing - removes |
| Patch | k patch deploy web -p '{"spec":{"replicas":4}}' |
| Edit | k edit deploy web |
| Rollouts | k rollout status, history, undo or restart deploy/web, --to-revision=2 |
| Replace a Pod | k replace --force -f pod.yaml |
| Apply, diff | k apply -f f.yaml, k diff -f f.yaml, k apply -k dir/ |
Read
| Goal | Command |
|---|---|
| Wide, labels | -o wide, --show-labels, -L app |
| Single field | -o jsonpath='{.items[*].metadata.name}' |
| Columns | -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName |
| Sort | --sort-by=.metadata.creationTimestamp |
| Filter | -l app=web, --field-selector status.phase=Running |
| Everywhere | -A |
| Fields | k explain pod.spec.containers.securityContext, --recursive |
| Kinds | k api-resources, k api-versions |
Debug
| Goal | Command |
|---|---|
| Logs | k logs p -c c --previous --tail=50 -f --since=10m |
| Shell | k exec -it p -c c -- sh |
| Throwaway Pod | k run t --rm -it --image=busybox:1.36 --restart=Never -- sh |
| Tunnel | k port-forward svc/web 8080:80 |
| Node shell | k debug node/n -it --image=busybox:1.36 |
| Copy | k cp ns/pod:/path ./local |
| Usage | k top node, k top pod -A --sort-by=memory |
| Events | k get events -A --sort-by=.lastTimestamp |
| Wait | k wait --for=condition=Ready pod/p --timeout=60s |
| Test RBAC | k auth can-i verb resource --as=user -n ns |
Contexts
k config get-contexts, k config use-context <name>, k config set-context --current --namespace=<ns>,
k config view --minify.