Kubernetes · Cheat sheet
kubectl cheat sheet
kubectl cheat sheet: contexts, inspect, debug, apply, rollouts, RBAC, and JSONPath — everyday commands with example output.
Rows marked Destructive State operation Caution Exposes secrets can remove data, change authoritative state, affect a running system, or print secrets. Read the note before running them against anything that matters.
Cluster & context
Beginnerkubectl version- Client and server versions (--short was removed in 1.28; compact output is the default).
kubectl cluster-info- Control-plane and CoreDNS endpoints.
kubectl config get-contexts- List every cluster you can talk to.Example output
CURRENT NAME CLUSTER NAMESPACE * prod prod default staging staging apps kubectl config use-context <ctx>- Switch the active cluster.
kubectl config set-context --current --namespace=<ns>- Pin a default namespace so you stop typing -n.
kubectl config current-context- Print just the active context name.
kubectl api-resources- Every resource kind, its short name and apiGroup.Example output
NAME SHORTNAMES APIVERSION NAMESPACED KIND pods po v1 true Pod services svc v1 true Service
kubectl api-versions- All served API group/versions.
Inspect resources
Beginnerkubectl get pods- Pods in the current namespace.
kubectl get pods -A- Pods in every namespace (--all-namespaces).
kubectl get pods -o wide- Add node, pod IP and nominated-node columns.Example output
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES web-0 1/1 Running 0 5m 10.1.3.7 node-2 <none> <none>
kubectl get all -n <ns>- Common objects (pods, svc, deploy, rs) at once.
kubectl get pods -w- Watch — stream status changes live.
kubectl get pods -l app=web- Filter by label selector.
kubectl get pods --field-selector status.phase=Running- Filter by a field, not a label.
kubectl get pods --sort-by=.status.startTime- Sort rows by any field path.
kubectl describe pod <p>- Events, conditions, and why it is not Running.
kubectl get events --sort-by=.lastTimestamp- Recent cluster events, oldest→newest.
kubectl events --for pod/<p> --watch- Events for one object, then stream new ones as they arrive.
kubectl get pod <p> -o yaml- Full live manifest of one object.
Create & run
Beginnerkubectl run web --image=nginx- Create a single pod imperatively.
kubectl create deployment web --image=nginx --replicas=3- Create a Deployment.
kubectl expose deployment web --port=80 --target-port=8080- Create a Service in front of it.
kubectl apply -f app.yaml- Create/update from a manifest (declarative).
kubectl apply -f .- Apply every manifest in the directory.
kubectl apply -k overlays/prod- Apply a Kustomize overlay.
kubectl create configmap cfg --from-file=./conf.d- ConfigMap from files in a directory.
kubectl create secret generic db --from-literal=pass=s3cr3tExposes secrets- Secret from a literal value.Exposes secrets: The value lands in shell history; prefer --from-file or --from-env-file.
kubectl create namespace <ns>- Create a namespace.
Edit, scale & rollout
Intermediatekubectl edit deploy/<d>- Open the live object in $EDITOR and apply on save.
kubectl scale deploy/<d> --replicas=5- Change replica count imperatively.
kubectl set image deploy/<d> app=nginx:1.30- Update one container image → triggers a rollout.
kubectl rollout status deploy/<d>- Watch a rollout to completion.Example output
Waiting for deployment "web" rollout to finish: 2 of 3 updated... deployment "web" successfully rolled out
kubectl rollout history deploy/<d>- List revisions you can roll back to.
kubectl rollout undo deploy/<d>Caution- Roll back to the previous revision.Caution: Rolls every pod back through a new rollout; config changes are reverted too.
kubectl rollout undo deploy/<d> --to-revision=3Caution- Roll back to a specific revision.Caution: Rolls every pod back through a new rollout; config changes are reverted too.
kubectl rollout restart deploy/<d>Caution- Rolling restart of all pods; images re-pull only if imagePullPolicy says so.Caution: Replaces every pod in the Deployment through a new rollout.
kubectl rollout pause deploy/<d>- Freeze a rollout so several spec changes land as one; kubectl rollout resume continues it.
kubectl delete deploy/<d> --cascade=orphanCaution- Delete the controller but keep its Pods.Caution: The ReplicaSets and Pods keep running with no owner; clean them up or re-adopt them.
kubectl autoscale deploy/<d> --min=2 --max=10 --cpu=70%- Create a HorizontalPodAutoscaler.
kubectl patch deploy/<d> -p '{"spec":{"replicas":4}}'- Strategic-merge patch one field.
kubectl label pod <p> tier=frontend --overwrite- Add or change a label in place.
kubectl annotate pod <p> note="drain me"- Attach non-identifying metadata.
Debug & logs
Intermediatekubectl logs <p>- Print a container’s logs.
kubectl logs <p> -f- Stream (follow) the logs.
kubectl logs <p> -c <ctr>- Logs from a specific container in the pod.
kubectl logs <p> --previous- Logs from the last crashed instance.
kubectl logs <p> --since=1h --tail=100- Last hour, last 100 lines.
kubectl exec -it <p> -- sh- Open a shell in a running container.
kubectl exec <p> -- envExposes secrets- Run a one-off command and print its output.Exposes secrets: Prints every env var, including values injected from Secrets.
kubectl cp <p>:/var/log/app.log ./app.log- Copy a file out of a container (needs tar in the image).
kubectl port-forward svc/<s> 8080:80- Tunnel a Service to localhost:8080.
kubectl debug <p> -it --image=busybox --target=<ctr>- Attach an ephemeral debug container.
kubectl debug node/<node> -it --image=busyboxCaution- Shell on a node without SSH.Caution: Runs a pod in the node's host namespaces with its filesystem at /host; treat it as root on the node.
kubectl top pod- Live CPU/memory per pod (needs metrics-server).Example output
NAME CPU(cores) MEMORY(bytes) web-0 3m 28Mi
kubectl top node- Live CPU/memory per node.
Manifests & dry-run
Intermediatekubectl apply -f app.yaml --dry-run=server- Validate against the API without persisting.
kubectl diff -f app.yaml- Show exactly what apply would change.
kubectl create deploy web --image=nginx --dry-run=client -o yaml- Generate a manifest instead of creating.Example output
apiVersion: apps/v1 kind: Deployment metadata: name: web ...
kubectl get deploy/<d> -o yaml > deploy.yaml- Export a live object to a file.
kubectl explain pod.spec.containers- Field-level docs for any resource.
kubectl replace -f app.yamlCaution- Replace an object wholesale (must exist).Caution: Fields missing from the file are dropped from the live object.
kubectl delete -f app.yamlDestructive- Delete everything defined in a manifest.Destructive: Deletes every object in the manifest, including any Namespace or PVC it defines.
kubectl delete pod <p> --grace-period=0 --forceCaution- Force-remove a stuck pod (last resort).Caution: Skips kubelet confirmation; a StatefulSet pod can briefly run twice.
Namespaces & RBAC
Advancedkubectl auth can-i create pods- Check your own permission.Example output
yes
kubectl auth can-i "*" "*" --all-namespaces- Am I effectively cluster-admin?
kubectl auth can-i list secrets --as=system:serviceaccount:app:build- Check what a ServiceAccount can do.
kubectl create serviceaccount build -n app- Create a ServiceAccount.
kubectl create role reader --verb=get,list --resource=pods -n app- Namespaced Role.
kubectl create rolebinding read-b --role=reader --serviceaccount=app:build -n app- Bind the Role to the SA.
kubectl create clusterrole nodes-ro --verb=get,list --resource=nodes- Cluster-scoped role.
kubectl get rolebindings,clusterrolebindings -A -o wide- Audit who is bound to what.
Nodes & scheduling
Advancedkubectl get nodes -o wide- Nodes with roles, versions and internal IPs.
kubectl cordon <node>Caution- Mark a node unschedulable (no new pods).Caution: No new pods land on the node until you uncordon it.
kubectl drain <node> --ignore-daemonsets --delete-emptydir-dataCaution- Evict pods to prep for maintenance.Caution: Evicts every pod on the node; emptyDir data on it is deleted.
kubectl uncordon <node>- Re-enable scheduling on the node.
kubectl taint nodes <node> key=value:NoScheduleCaution- Repel pods that lack the matching toleration.Caution: New pods without a matching toleration stop landing on the node.
kubectl taint nodes <node> key:NoSchedule-- Remove a taint (trailing dash).
kubectl label node <node> disk=ssd- Label a node for nodeSelector/affinity.
kubectl describe node <node>- Capacity, allocatable, taints, and running pods.
JSONPath & power-user
Advancedkubectl get pods -o jsonpath='{.items[*].metadata.name}'- Extract just the fields you need.Example output
web-0 web-1 api-0
kubectl get pod <p> -o jsonpath='{.status.containerStatuses[0].restartCount}'- Pull one scalar out of an object.
kubectl get svc -o custom-columns=NAME:.metadata.name,IP:.spec.clusterIP- Define your own table columns.
kubectl wait --for=condition=Ready pod/<p> --timeout=120s- Block in scripts until a condition holds.
kubectl apply --server-side -f app.yaml- Server-side apply — safer field ownership.
kubectl get --raw /metrics- Hit an API endpoint directly (raw).
kubectl proxy --port=8001- Local authenticated proxy to the API server.
kubectl certificate approve <csr>Caution- Approve a pending CertificateSigningRequest.Caution: Issues a credential for the CSR's user and groups; inspect the CSR first.
kubectl get pods -o json | jq '.items[].metadata.name'- Pipe JSON to jq for anything JSONPath cannot do.
Related
- Cheat sheetHelm cheat sheet
- Cheat sheetKustomize cheat sheet
- ComparisonHelm vs Kustomize
- Interview guideKubernetes interview questions
- CourseKubernetes fundamentals
- CourseKubernetes administration
- CourseKubernetes security & hardening
- Field noteDebugging Pending pods: the five usual causes
- Field noteKubernetes liveness, readiness, startup probes done right
- Field noteKubernetes requests and limits: stop OOMKills, noisy pods
Primary references
Found a technical issue on this page? Report it with the tool version you used and the behavior you saw. How resources are maintained.
Go deeper
Hands-on courses for Kubernetes