kubectl cheat sheet for hands-on exams

The commands that save the most time when you're solving tasks on a live cluster, grouped by what you're trying to do.

Last reviewed . Image tags and versions are examples. Check flags against kubectl <command> --help for your cluster's version.

Contexts and namespaces

CommandWhat it does
kubectl config get-contextsList contexts; the current one has a *
kubectl config use-context <name>Switch cluster: run the one from the task first
kubectl config current-contextConfirm where you are
kubectl get pods -n <ns>Name the namespace on every command
kubectl get pods -AAll namespaces

Generate YAML instead of typing it

CommandWhat it does
export do="--dry-run=client -o yaml"Shortcut used below
kubectl run web --image=nginx:1.27 --port=80 $do > pod.yamlPod skeleton
kubectl create deploy web --image=nginx:1.27 --replicas=3 $doDeployment skeleton
kubectl create job once --image=busybox:1.36 $do -- dateJob
kubectl create cronjob tick --image=busybox:1.36 --schedule="*/5 * * * *" $do -- dateCronJob
kubectl create cm app --from-literal=MODE=prod --from-file=app.conf $doConfigMap
kubectl create secret generic db --from-literal=PASS=s3cret $doSecret
kubectl expose deploy web --port=80 --target-port=8080 --type=NodePort $doService for a Deployment
kubectl create ingress web --rule='app.lab.internal/=web:80' $doIngress
kubectl get deploy web -o yaml > web.yamlStart from a live object

Change things

CommandWhat it does
kubectl apply -f file.yamlCreate or update from a file
kubectl edit deploy web -n appEdit live (opens $EDITOR)
kubectl replace --force -f pod.yamlDelete and recreate, for immutable Pod fields
kubectl set image deploy/web nginx=nginx:1.28Change a container image
kubectl scale deploy web --replicas=5Scale
kubectl autoscale deploy web --min=2 --max=6 --cpu-percent=70HorizontalPodAutoscaler
kubectl label node node01 disk=ssdAdd a label (--overwrite to change one)
kubectl label node node01 disk-Remove a label
kubectl taint node node01 dedicated=gpu:NoScheduleAdd a taint ('-' at the end removes it)
kubectl patch deploy web -p '{"spec":{"replicas":2}}'Small merge patch

Rollouts

CommandWhat it does
kubectl rollout status deploy/webWait for a rollout to finish
kubectl rollout history deploy/webRevisions
kubectl rollout undo deploy/web --to-revision=2Roll back
kubectl rollout restart deploy/webRestart all Pods, e.g. after a ConfigMap change
kubectl rollout pause deploy/webBatch several changes into one rollout (resume to continue)

Nodes and cluster lifecycle

CommandWhat it does
kubectl cordon node01Stop new Pods landing on a node
kubectl drain node01 --ignore-daemonsets --delete-emptydir-dataEvict Pods before maintenance
kubectl uncordon node01Back in service
kubeadm upgrade planShow available upgrades (control plane)
kubeadm upgrade apply v1.X.YUpgrade the first control-plane node
kubeadm upgrade nodeUpgrade other nodes, then the kubelet package
kubeadm token create --print-join-commandCommand for joining a new worker
kubeadm certs check-expirationWhen the cluster's certificates expire

etcd backup and restore

CommandWhat it does
ETCDCTL_API=3 etcdctl snapshot save /opt/backup.db --endpoints=https://127.0.0.1:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.keySnapshot (paths as on a kubeadm control plane)
etcdutl snapshot status /opt/backup.db -w tableCheck the snapshot
etcdutl snapshot restore /opt/backup.db --data-dir=/var/lib/etcd-restoredRestore into a new directory
grep -A2 etcd-data /etc/kubernetes/manifests/etcd.yamlThen point the etcd static Pod's data volume at it

Access control

CommandWhat it does
kubectl create sa builder -n ciServiceAccount
kubectl create role deployer --verb=get,list,create,update --resource=deployments -n ciRole
kubectl create rolebinding deployer --role=deployer --serviceaccount=ci:builder -n ciBind it
kubectl auth can-i create deployments --as=system:serviceaccount:ci:builder -n ciProve it works
kubectl auth can-i --list --as=jane -n devEverything a user may do
kubectl certificate approve janeApprove a CertificateSigningRequest

Debugging

CommandWhat it does
kubectl describe pod web-x -n appEvents at the bottom say why
kubectl get events -n app --sort-by=.lastTimestampRecent events, newest last
kubectl logs web-x -c sidecar --previousLogs of the last crashed container
kubectl logs deploy/web --all-containers --since=10mLogs across a Deployment
kubectl exec -it web-x -- shShell inside a container
kubectl debug -it web-x --image=busybox:1.36 --target=webEphemeral debug container
kubectl run t --rm -it --image=busybox:1.36 --restart=Never -- wget -qO- http://web.appTest a Service from inside the cluster
kubectl top pods -A --sort-by=memoryResource use (needs metrics-server)
crictl ps -aContainers on a node, even when the API server is down
journalctl -u kubelet -fKubelet log on a node

Networking and storage

CommandWhat it does
kubectl get svc,endpointslices -n appDoes the Service have endpoints?
kubectl get pods -n app --show-labelsCompare Pod labels with the Service selector
kubectl get netpol -ANetworkPolicies that might block traffic
kubectl get gateway,httproute -AGateway API objects
kubectl get scStorageClasses; the default is marked
kubectl get pv,pvc -AVolumes and their claims, with status

Output formats

CommandWhat it does
kubectl get pods -o wideNode and Pod IP
kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")].address}'One field from every item
kubectl get pods -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeNameYour own table
kubectl get pods --sort-by=.metadata.creationTimestampSort
kubectl get pods -l app=web,tier!=cacheFilter by label
kubectl get pods --field-selector=status.phase!=RunningFilter by field
kubectl explain deploy.spec.strategy --recursiveField reference without leaving the terminal

Use them on a real cluster

Every lab gives you a kubeadm cluster with root on both nodes, so every command on this page works there.