Commands · Reference

☸️Kubernetes Commands

kubectl grouped by task — inspect, change, debug, and the output flags that make it scriptable instead of something you read.

Inspecting

11 commands

get tells you what exists, describe tells you why it is unhappy. Events at the bottom of describe answer most questions on their own.

CommandWhat it does Typical use
kubectl get po -o widePods with node, IP and nominated nodekubectl get po -o wide
kubectl get po -AAcross every namespacekubectl get po -A | grep -v Running
kubectl get po --field-selector status.phase!=RunningOnly what is not healthykubectl get po -A --field-selector status.phase!=Running
kubectl get po -l app=apiBy label — the way controllers selectkubectl get po -l 'app in (api,web)'
kubectl get po --sort-by=.status.containerStatuses[0].restartCountWorst restart offenders firstkubectl get po --sort-by=.status.containerStatuses[0].restartCount
kubectl get ev --sort-by=.lastTimestampEvents in time order, not the default jumblekubectl get ev -A --sort-by=.lastTimestamp | tail -30
kubectl describe po NAMEFull state plus the events for that objectkubectl describe po api-7d4f-x9k2
kubectl get all -n NSThe common workload kinds in one namespacekubectl get all -n payments
kubectl api-resourcesEvery kind the cluster knows, with short nameskubectl api-resources --namespaced=true
kubectl explain po.spec.containersField documentation straight from the API serverkubectl explain deploy.spec.strategy --recursive
kubectl top po --sort-by=memoryLive usage — needs metrics-serverkubectl top po -A --sort-by=memory

Applying & deleting

10 commands

apply is declarative and records intent in an annotation; create is imperative and fails if the object exists. Use apply.

CommandWhat it does Typical use
kubectl apply -f dir/ -RApply a directory treekubectl apply -f k8s/ -R
kubectl apply --dry-run=serverAsk the API server what would happen, admission and allkubectl apply -f d.yaml --dry-run=server
kubectl diff -fDiff your manifest against the live object before applyingkubectl diff -f deploy.yaml
kubectl create … --dry-run=client -o yamlGenerate a manifest skeleton to editkubectl create deploy api --image=nginx --dry-run=client -o yaml
kubectl patch -pChange one field without sending the whole objectkubectl patch deploy api -p '{"spec":{"replicas":5}}'
kubectl set imageChange an image and trigger a rolloutkubectl set image deploy/api api=repo/api:v2
kubectl editOpen the live object in $EDITOR. Fine for triage, bad as a habitkubectl edit deploy api
kubectl delete --grace-period=0 --forceLast resort for a stuck pod; it can orphan resourceskubectl delete po stuck --grace-period=0 --force
kubectl replace --forceDelete and recreate — for immutable field changeskubectl replace --force -f job.yaml
kubectl label / annotate --overwriteAdd or change metadata in placekubectl label no worker-3 tier=spot --overwrite

Logs, exec & debugging

11 commands

The order that finds it fastest: logs, then previous logs, then events, then exec. If the container will not start, exec is not available — use debug.

CommandWhat it does Typical use
kubectl logs -f --tail=100Follow the last 100 lineskubectl logs -f --tail=100 api-7d4f
kubectl logs --previousLogs from the container that just crashed. The important onekubectl logs api-7d4f --previous
kubectl logs -l app=api --max-log-requests=10Aggregate logs across pods by labelkubectl logs -l app=api --tail=50 --prefix
kubectl logs --since=15m --timestampsTime-bounded, with timestampskubectl logs api-7d4f --since=15m --timestamps
kubectl exec -it -- shShell in a running containerkubectl exec -it api-7d4f -c api -- sh
kubectl debug -it --image=nicolaka/netshootAttach an ephemeral container with real toolskubectl debug -it api-7d4f --image=nicolaka/netshoot --target=api
kubectl debug node/NAME -it --image=ubuntuA privileged pod on a node, with its root at /hostkubectl debug node/worker-3 -it --image=ubuntu
kubectl run tmp --rm -it --image=busybox -- shThrowaway pod for a quick testkubectl run tmp --rm -it --image=busybox --restart=Never -- sh
kubectl port-forwardReach a pod or service from your laptopkubectl port-forward svc/api 8080:80
kubectl cpCopy files in or out of a containerkubectl cp api-7d4f:/tmp/heap.hprof ./heap.hprof
kubectl attach -itAttach to PID 1's stdio, rather than starting a new processkubectl attach -it api-7d4f

Rollouts & scaling

8 commands

A rollout is a new ReplicaSet gradually taking over from the old one. rollout status blocks until it settles, which makes it usable in CI.

CommandWhat it does Typical use
kubectl rollout status --timeout=5mWait for a rollout, fail the pipeline if it stallskubectl rollout status deploy/api --timeout=5m
kubectl rollout historyRevisions, with the change-cause annotationkubectl rollout history deploy/api
kubectl rollout undo --to-revision=3Roll back to a specific revisionkubectl rollout undo deploy/api --to-revision=3
kubectl rollout restartRestart every pod without changing the spec — picks up new secretskubectl rollout restart deploy/api
kubectl rollout pause / resumeHold a rollout mid-flight to inspect itkubectl rollout pause deploy/api
kubectl scale --replicas=0Scale to zero and back — the crudest restartkubectl scale deploy/api --replicas=0
kubectl autoscale --min --max --cpu-percentCreate an HPA imperativelykubectl autoscale deploy/api --min=2 --max=10 --cpu-percent=70
kubectl wait --for=condition=ReadyBlock until a condition holds — for scriptskubectl wait --for=condition=Ready po -l app=api --timeout=120s

Nodes & scheduling

7 commands

Draining is two steps: cordon stops new pods, drain evicts the existing ones respecting PodDisruptionBudgets.

CommandWhat it does Typical use
kubectl get no -o wideNodes with version, OS image and kernelkubectl get no -o wide
kubectl describe no NAMEConditions, allocatable, and what is already on itkubectl describe no worker-3
kubectl cordon / uncordonStop / resume scheduling onto a nodekubectl cordon worker-3
kubectl drain --ignore-daemonsets --delete-emptydir-dataEvict everything before maintenancekubectl drain worker-3 --ignore-daemonsets --delete-emptydir-data
kubectl taint no key=value:NoScheduleRepel pods that lack the matching tolerationkubectl taint no worker-3 gpu=true:NoSchedule
kubectl get po --field-selector spec.nodeName=XWhat is running on one nodekubectl get po -A --field-selector spec.nodeName=worker-3
kubectl describe no | grep -A5 AllocatedHow much of the node is already requestedkubectl describe no worker-3 | grep -A6 'Allocated resources'

Contexts, config & access

7 commands

kubectl config edits your kubeconfig; auth can-i answers RBAC questions without trial and error.

CommandWhat it does Typical use
kubectl config get-contextsEvery cluster you can reach, and which is currentkubectl config get-contexts
kubectl config use-contextSwitch clusterkubectl config use-context prod-eu
kubectl config set-context --current --namespace=Stop typing -n on every commandkubectl config set-context --current --namespace=payments
kubectl auth can-i --listEverything the current identity may do herekubectl auth can-i --list -n payments
kubectl auth can-i delete po --as=Check another user's or service account's rightskubectl auth can-i delete po --as=system:serviceaccount:ci:deployer
kubectl auth whoamiWhich identity the API server seeskubectl auth whoami
kubectl get secret NAME -o jsonpath='{.data.k}' | base64 -dRead one key out of a secretkubectl get secret db -o jsonpath='{.data.password}' | base64 -d

Output & scripting

8 commands

Everything above becomes automatable with the right -o. jsonpath for one value, -o json | jq for anything complex.

CommandWhat it does Typical use
-o jsonpath='{.items[*].metadata.name}'Pull specific fieldskubectl get po -o jsonpath='{.items[*].spec.nodeName}'
-o custom-columns=Build your own tablekubectl get po -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName
-o yaml / -o jsonThe full object as the API server holds itkubectl get deploy api -o yaml
--no-headersMachine-readable output for a pipelinekubectl get po --no-headers | wc -l
-w / --watchStream changes as they happenkubectl get po -w
kubectl get --raw /metricsHit an API server endpoint directlykubectl get --raw /readyz?verbose
kubectl kustomize dir/Render a kustomization without applying itkubectl kustomize overlays/prod | less
kubectl--v=8Log every HTTP request kubectl makes — the debugging escape hatchkubectl get po --v=8
← PreviousLinux Commands