kubectl Cheat Sheet: Commands by Task, Checked on v1.37
DevOps Engineering

kubectl Cheat Sheet: Commands by Task, Checked on v1.37

kubectl commands grouped by task: debug pods, roll back, drain nodes. Checked against Kubernetes v1.37.

Michael Zion

16 min read

Most kubectl cheat sheets list commands by resource type. This one lists them by what you are trying to do, and every flag in it was checked against the Kubernetes v1.37 reference on November 18, 2026.

Bottom line

12 commands cover most days:

You want toRun
Know which cluster you are about to changekubectl config current-context
List the pods that are not runningkubectl get pods -A --field-selector=status.phase!=Running
Know why a pod is unhealthykubectl describe pod POD
Read the logs of the container that just crashedkubectl logs POD --previous
See only the warningskubectl events --types=Warning
Get a shell in a containerkubectl exec -it POD -- sh
Get a shell when the image has no shellkubectl debug -it POD --image=busybox:1.28 --target=CONTAINER
Reach a service from your laptopkubectl port-forward svc/SERVICE 8080:80
See a change before you make itkubectl diff -f FILE.yaml
Restart every pod of a Deployment, graduallykubectl rollout restart deployment/NAME
Go back to the previous versionkubectl rollout undo deployment/NAME
Check your permissions before you trykubectl auth can-i delete pods -n NAMESPACE

Words in capitals are placeholders. Replace them with your own names.

The second command filters on the pod phase. A pod in CrashLoopBackOff, or one that runs with 0/1 containers ready, still has the phase Running and stays out of that list, and finished Job pods show up in it. For those, read the READY and STATUS columns of kubectl get pods -A.

Do you open this page during incidents? A senior engineer spends an hour on your CI/CD, infra, Kubernetes, cloud cost and on-call setup. You leave with your top 3 risks, quick wins and a rough roadmap. Claim your free assessment.

Find your task:

Setup: completion, an alias and the right cluster

Tab completion and a 1-letter alias, for bash:

source <(kubectl completion bash)
alias k=kubectl
complete -o default -F __start_kubectl k

For zsh, add this to ~/.zshrc:

source <(kubectl completion zsh)

Then the commands that tell you where you are:

TaskCommand
List the clusters in your kubeconfigkubectl config get-contexts
Show the active onekubectl config current-context
Switch clusterkubectl config use-context CONTEXT
Set the default namespace for the active contextkubectl config set-context --current --namespace=NAMESPACE
Run 1 command against another cluster without switchingkubectl --context=CONTEXT get pods
Show client and server versionskubectl version
List every resource type the cluster knowskubectl api-resources
Read the documentation of a fieldkubectl explain pod.spec.containers.resources

The classic kubectl accident is a correct command sent to the wrong cluster. In scripts and runbooks, write --context and -n on every command. A script that depends on whatever context your terminal had last is a script that will delete staging in production one day.

Keep kubectl within 1 minor version of the cluster. The version skew policy says: "kubectl is supported within one minor version (older or newer) of kube-apiserver." The latest stable release today is v1.37.2, and the supported minors are 1.37, 1.36 and 1.35.

Look at things: get, describe and output formats

TaskCommand
Pods in every namespacekubectl get pods -A
Pods with their node and IPkubectl get pods -o wide
Pods by labelkubectl get pods -l app=web
Pods on 1 nodekubectl get pods -A --field-selector=spec.nodeName=NODE
Pods sorted by restartskubectl get pods --sort-by='.status.containerStatuses[0].restartCount'
Newest objects lastkubectl get pods --sort-by=.metadata.creationTimestamp
Watch changes livekubectl get pods -w
A label as a columnkubectl get pods -L app
The full objectkubectl get deployment NAME -o yaml
Names only, for pipingkubectl get pods -o name
Only the status partkubectl get pod POD -o jsonpath='{.status}'
The human summary with eventskubectl describe pod POD

Label selectors (-l) support =, !=, in and notin. Field selectors support only =, == and !=, and the reference adds: "The server only supports a limited number of field queries per type."

Pull out 1 field with JSONPath

# Every image running in the cluster
kubectl get pods -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"\t"}{.metadata.name}{"\t"}{.spec.containers[*].image}{"\n"}{end}'

# One key of a Secret, decoded
kubectl get secret NAME -o jsonpath='{.data.password}' | base64 -d

# A key with a dot in its name
kubectl get secret NAME -o jsonpath='{.data.ca\.crt}' | base64 -d

JSONPath in kubectl has no regular expressions. The docs say to use jq for that.

Build your own table with custom-columns

kubectl get pods -o custom-columns='NAME:.metadata.name,NODE:.spec.nodeName,IMAGE:.spec.containers[*].image'

Why "get all" misses things

kubectl get all does not return all. all is a category that resource types opt into. In the Kubernetes source today it covers pods, services, deployments, replicasets, statefulsets, daemonsets, jobs, cronjobs, replicationcontrollers and horizontalpodautoscalers. ConfigMaps, Secrets, Ingresses, PersistentVolumeClaims, ServiceAccounts, Roles and NetworkPolicies are missing, and so are most custom resources.

To list everything in a namespace:

kubectl api-resources --verbs=list --namespaced -o name \
  | xargs -n 1 kubectl get --show-kind --ignore-not-found -n NAMESPACE

Run it before you delete a namespace you did not create.

Debug a pod by its status

Start from the STATUS column of kubectl get pods. Each status has a first command.

StatusWhat it meansFirst command
PendingNo node accepted the pod, or its volume is not readykubectl describe pod POD, then read the Events at the bottom
ImagePullBackOff, ErrImagePullThe node cannot pull the image: wrong tag, private registry, missing pull secretkubectl events --for pod/POD
CrashLoopBackOffThe container starts, exits and gets restarted with a growing delaykubectl logs POD --previous
OOMKilledThe container went over its memory limit and the kernel killed itkubectl describe pod POD, then read Last State
Running with 0/1 readyThe readiness probe failskubectl describe pod POD, then kubectl logs POD
Terminating for minutesA finalizer or an unreachable node holds the podkubectl get pod POD -o jsonpath='{.metadata.finalizers}'

The glossary has a page for each of the 3 most common ones: CrashLoopBackOff, ImagePullBackOff and OOMKilled.

Four pod statuses and the first command for each: Pending, kubectl describe pod. ImagePullBackOff, kubectl events --for pod. CrashLoopBackOff, kubectl logs --previous. OOMKilled, kubectl top pod --containers
The first command for the 4 statuses you will meet most.

The reason the last container died, without scrolling through describe:

kubectl get pod POD -o jsonpath='{.status.containerStatuses[*].lastState.terminated.reason}'

If the answer is OOMKilled, compare real usage with the limit before you raise it (how to set requests and limits):

kubectl top pod POD --containers

kubectl top needs Metrics Server in the cluster. It reports CPU and memory only, and a new pod has no numbers for the first minutes.

Logs

TaskCommand
Follow the logskubectl logs -f POD
The container that ran before the last restartkubectl logs POD --previous
1 container of a pod with severalkubectl logs POD -c CONTAINER
Every container of the podkubectl logs POD --all-containers
The last 15 minuteskubectl logs POD --since=15m
The last 100 lines, with timestampskubectl logs POD --tail=100 --timestamps
Every pod of a Deploymentkubectl logs deployment/NAME --all-pods
Every pod with a label, each line marked with its podkubectl logs -l app=web --prefix --tail=50

3 details that cost people time:

  • kubectl logs deployment/NAME without --all-pods reads 1 pod. The flag arrived in kubectl 1.31.
  • With a label selector, --tail defaults to 10 lines per pod, and -f stops with an error when the selector matches more than 5 pods. Raise that limit with --max-log-requests.
  • --previous reads the previous container of the same pod. Once the pod is deleted, those logs are gone from kubectl. A log pipeline is the only thing that keeps them.

Events

kubectl events --for pod/POD
kubectl events --types=Warning
kubectl events -A --types=Warning --watch

kubectl events has been a top-level command since 1.26. It sorts by time on its own, which kubectl get events does not. If you are on muscle memory, kubectl get events --sort-by=.metadata.creationTimestamp still works.

Shell, files and ports

TaskCommand
A shell in the podkubectl exec -it POD -- sh
1 command in 1 containerkubectl exec POD -c CONTAINER -- env
A command in the first pod of a Deploymentkubectl exec deployment/NAME -- date
Copy a file out of a podkubectl cp NAMESPACE/POD:/tmp/dump.hprof ./dump.hprof
Local port 8080 to port 80 of a Servicekubectl port-forward svc/SERVICE 8080:80
Local port 5432 to a podkubectl port-forward pod/POD 5432:5432

The -- before the command is required. The form without it was removed in kubectl 1.31, and some cheat sheets that rank today still print it.

kubectl cp needs the tar binary inside the container. On a distroless image it fails, which brings us to the next command.

kubectl debug: when exec is not enough

kubectl exec can only run a binary that exists in the image. A distroless image has no shell and no tools, and a crashing container does not stay up long enough to exec into. kubectl debug covers both, in 3 modes.

ModeCommandUse it when
Ephemeral container in the running podkubectl debug -it POD --image=busybox:1.28 --target=CONTAINERThe pod runs and the image has no tools
Copy of the podkubectl debug POD -it --copy-to=POD-debug --container=CONTAINER -- shThe container crashes at start and you want it with another command
Pod on the nodekubectl debug node/NODE -it --image=busybox:1.28The problem is the node and you have no SSH
The 3 modes of kubectl debug: an ephemeral container inside the running pod, a copy of the pod, and a debug pod on the node with the host filesystem at /host
The 3 modes of kubectl debug.
  • --target puts the debug container in the process namespace of the named container, so ps shows its processes. The container runtime has to support it.
  • An ephemeral container stays in the pod spec until the pod is replaced. It never restarts, and you cannot add one with kubectl edit.
  • In node mode the node's filesystem is mounted at /host.
  • Delete the copy and the node pod when you are done. Nothing cleans them up for you.

--profile sets how much power the debug container gets: general, baseline, restricted, netadmin or sysadmin. The default changed from legacy to general in kubectl 1.36, and legacy is planned for removal in 1.39. Use --profile=sysadmin when you need root on a node, and --profile=restricted in namespaces that enforce the restricted Pod Security Standard.

(One official page still says the default is legacy. The v1.37 command reference and the 1.36 changelog say general.)

Change things safely

The order I use for any change to a cluster that matters: diff, server dry run, apply.

kubectl diff -f deploy.yaml
kubectl apply -f deploy.yaml --dry-run=server
kubectl apply -f deploy.yaml
  • kubectl diff exits with 0 when nothing would change, 1 when something would, and more than 1 on an error. That makes it a 1-line drift check in CI.
  • --dry-run=server sends the request through admission and validation without saving it. --dry-run=client only prints the object. Always write the value: the bare --dry-run has been deprecated since 1.18.
  • kubectl apply -k DIRECTORY applies a kustomization the same way.

Let kubectl write the YAML

kubectl create deployment web --image=nginx:1.27 --dry-run=client -o yaml > deploy.yaml
kubectl create secret generic db --from-literal=password=CHANGE_ME --dry-run=client -o yaml
kubectl create configmap app-config --from-file=config.yaml --dry-run=client -o yaml
kubectl create job manual-run --from=cronjob/NAME

The last line runs a CronJob once, now. It is the fastest way to test one without waiting for the schedule.

Quick edits

TaskCommand
Change the imagekubectl set image deployment/NAME CONTAINER=IMAGE:TAG
Change an environment variablekubectl set env deployment/NAME KEY=value
Change a memory limitkubectl set resources deployment/NAME -c CONTAINER --limits=memory=512Mi
Scalekubectl scale deployment/NAME --replicas=3
Patch 1 fieldkubectl patch deployment NAME -p '{"spec":{"replicas":3}}'
Add or change a labelkubectl label pods POD team=payments --overwrite
Remove a labelkubectl label pods POD team-
Open the live object in your editorkubectl edit deployment/NAME

If Argo CD or Flux owns the object, these edits last until the next sync. If Helm owns it, they last until the next helm upgrade. Use them to stop an incident, then put the same change in Git.

apply, create or replace

  • apply sends only the differences and keeps fields that other writers set. Use it for everything that lives in a file.
  • create fails when the object exists. Use it for one-off objects and for generating YAML.
  • replace swaps the whole spec and drops whatever is missing from your file. replace --force deletes and recreates the object, and the official quick reference marks it: "Will cause a service outage."

Pick 1 per object. The docs are blunt about it: "Mixing and matching techniques for the same object results in undefined behavior."

kubectl apply --server-side moves the merge to the API server and records which tool owns each field. When another tool owns a field you are changing, the request is rejected until you pass --force-conflicts. Read the conflict before you force it: it is usually your autoscaler or your GitOps controller telling you the field is taken.

Rollouts: restart, watch and undo

TaskCommand
Wait for a rollout to finishkubectl rollout status deployment/NAME --timeout=120s
Restart every pod, one batch at a timekubectl rollout restart deployment/NAME
Restart every Deployment with a labelkubectl rollout restart deployment --selector=app=web
List the revisionskubectl rollout history deployment/NAME
Go back 1 revisionkubectl rollout undo deployment/NAME
Go back to a specific revisionkubectl rollout undo deployment/NAME --to-revision=2
Freeze a rollout halfwaykubectl rollout pause deployment/NAME
Continue itkubectl rollout resume deployment/NAME

rollout restart is the answer to "the app did not pick up the new ConfigMap". It follows the Deployment's update strategy. With the default RollingUpdate strategy, 2 or more replicas and a readiness probe, nobody notices. With the Recreate strategy every pod stops first.

rollout undo has the same catch as the quick edits: a GitOps controller will roll you forward again on its next sync. Revert the commit too.

Wait for something in a script

kubectl wait --for=condition=Available deployment/NAME --timeout=120s
kubectl wait --for=condition=Ready pod -l app=web --timeout=60s
kubectl wait --for=condition=Complete job/NAME --timeout=10m
kubectl wait --for=delete pod/POD --timeout=60s
kubectl wait --for=jsonpath='{.status.phase}'=Running pod/POD

The default timeout is 30 seconds, so set it. kubectl wait replaces every sleep 30 in a pipeline, and it fails the step when the thing never becomes ready. One catch: waiting for condition=Complete on a Job that failed runs until the timeout, because a failed Job never gets that condition.

Nodes: cordon, drain and uncordon

kubectl cordon NODE
kubectl drain NODE --ignore-daemonsets --delete-emptydir-data --timeout=300s
# patch, reboot or replace the node
kubectl uncordon NODE

cordon stops new pods from landing on the node. drain cordons first and then evicts what runs there. A plain kubectl drain NODE stops on most real nodes, because of what drain refuses to touch by default:

On the nodeWhat drain doesFlag
DaemonSet podsRefuses to proceed. With the flag it skips them, since the DaemonSet would recreate them at once--ignore-daemonsets
Pods with an emptyDir volumeRefuses, because the data dies with the pod--delete-emptydir-data
Pods with no controllerRefuses, because nothing would recreate them--force
Pods under a PodDisruptionBudget with no room leftWaits and retries until the budget allows the eviction--timeout to give up
What kubectl drain refuses by default and the flag for each: DaemonSet pods need --ignore-daemonsets, pods with emptyDir need --delete-emptydir-data, pods with no controller need --force, and a full PodDisruptionBudget makes drain wait
What drain refuses by default, and the flag for each case.

There is a flag that skips PodDisruptionBudgets, --disable-eviction, and its own help text says "use with caution". A drain that hangs on a budget is doing its job. Fix the budget or add a replica. The longer version is in how to drain Kubernetes nodes without evicting critical workloads.

Other node commands:

kubectl top node
kubectl describe node NODE
kubectl taint nodes NODE dedicated=batch:NoSchedule
kubectl taint nodes NODE dedicated=batch:NoSchedule-

The trailing - on the last line removes the taint.

Check access: can-i and whoami

kubectl auth whoami
kubectl auth can-i create deployments -n NAMESPACE
kubectl auth can-i --list -n NAMESPACE
kubectl auth can-i list secrets -n NAMESPACE --as=system:serviceaccount:NAMESPACE:SERVICEACCOUNT

The last one answers "can this workload read Secrets?" without deploying anything. -q prints nothing and only sets the exit code, for scripts.

If kubectl exec or port-forward returns a permission error after an upgrade to 1.35: since that release the API server requires create on pods/exec, pods/attach and pods/portforward for every request. Roles that only granted get on them no longer work.

When a command behaves in a way you cannot explain, add --v=6 to see every API request kubectl makes, and --v=8 to see the request bodies.

Delete commands that hurt

CommandWhat it really does
kubectl delete pod PODAsks the pod to stop and gives it its grace period, 30 seconds by default
kubectl delete pod POD --nowSame as --grace-period=1. The pod still gets a signal and 1 second
kubectl delete pod POD --grace-period=0 --forceRemoves the pod from the API at once and does not wait for the node to confirm that the processes stopped
kubectl delete pods --allDeletes every pod in the current namespace. Whichever namespace that is
kubectl delete namespace NAMESPACEDeletes everything in the namespace. The docs put an exclamation mark on that sentence
kubectl delete -f DIRECTORY/Deletes every object defined in every manifest of the directory
kubectl replace --force -f FILE.yamlDeletes and recreates. An outage for a Deployment
kubectl delete deployment NAME --cascade=orphanDeletes the Deployment and leaves its pods running
How long a pod gets to stop: 30 seconds by default with kubectl delete pod, 1 second with --now, and no wait and no confirmation with --grace-period=0 --force
How long a pod gets to stop, by flag.

Force delete deserves a paragraph. The reference warns that it "does not wait for confirmation that the pod's processes have been terminated, which can leave those processes running". For a stateless web pod that is harmless. For a StatefulSet pod it can mean 2 copies of the same database member writing at once, and the StatefulSet docs name the result: data loss. If a pod is stuck in Terminating, find out what holds it (a finalizer, or a node that is gone) before you reach for --force. When the node is dead for good, the documented fix is to delete the Node object.

Also worth knowing: deleting a pod or a Deployment bypasses PodDisruptionBudgets. Only evictions, like the ones drain sends, respect them.

2 habits that prevent most of the table:

kubectl delete pods --all -n NAMESPACE --dry-run=server
kubectl delete pods --all -n NAMESPACE --interactive

The first prints what would be deleted. The second lists the objects and asks for a yes. --interactive (short: -i) has been on by default since kubectl 1.29 and stable since 1.30.

kuberc: make the safe flags your default

kuberc is a preferences file for kubectl, separate from your kubeconfig. It holds aliases and default flags and no credentials. It has been beta and on by default since kubectl 1.34, and the changelog of the upcoming 1.38 graduates it to stable, with kubectl.config.k8s.io/v1 as the API version.

The file lives at ~/.kube/kuberc. This version makes every delete ask for confirmation and adds an alias:

apiVersion: kubectl.config.k8s.io/v1beta1
kind: Preference
defaults:
  - command: delete
    options:
      - name: interactive
        default: "true"
aliases:
  - name: getn
    command: get
    options:
      - name: output
        default: json

A flag you type always wins over the default, so kubectl delete pod POD --interactive=false still skips the prompt. To switch the file off for 1 shell, set KUBERC=off. CI runners have no kuberc unless you put one there, so your pipelines are not affected. A script you run on your own laptop is: give its delete commands --interactive=false, or it will stop and wait for an answer.

The kubectl maintainers suggest 2 more settings: server-side apply as the default for kubectl apply, and a policy for credential plugins. I would add server-side apply per team, after you check which tools already own fields in your cluster. Their example sets the credential plugin policy to DenyAll, and the same page tells users of managed Kubernetes to use an allowlist, since those clusters log you in through such a plugin.

Old commands that no longer work

If a command from an older cheat sheet or a Stack Overflow answer fails, it is probably in this table.

Old formStatusUse now
kubectl exec POD lsRemoved in 1.31kubectl exec POD -- ls
kubectl run NAME --replicas=3run only creates pods since 1.18, flag removed in 1.21kubectl create deployment NAME --image=IMAGE --replicas=3
kubectl rolling-updateRemoved in 1.18kubectl set image and kubectl rollout
kubectl get TYPE NAME -o yaml --exportDeprecated in 1.14 and removedkubectl get TYPE NAME -o yaml, then clean the status and metadata by hand
kubectl get componentstatusesAPI deprecated in 1.19kubectl get --raw='/readyz?verbose' (API server and etcd checks only)
kubectl alpha events, kubectl alpha debugPromoted in 1.26 and 1.20kubectl events, kubectl debug
kubectl apply --server-dry-runReplaced in 1.18kubectl apply --dry-run=server
kubectl delete --cascade=falseThe documented values are background, orphan and foreground--cascade=orphan
kubectl top namespace, kubectl create podDo not exist, and a cheat sheet that ranks today still prints themkubectl top pod -n NAMESPACE --sum, kubectl run

1 more thing that looks deprecated and is not: kubectl apply --prune. It has carried an alpha warning since kubectl 1.5, and its replacement, ApplySets, has been alpha since 1.27. If you want deleted manifests to delete objects, that is a job for Argo CD, Flux or Helm today.

Plugins

A kubectl plugin is any executable on your PATH whose name starts with kubectl-. A file named kubectl-foo gives you kubectl foo. Plugins cannot replace built-in commands.

kubectl plugin list

Krew is the plugin manager maintained by the Kubernetes CLI group. Before you install from it on a laptop that holds production credentials, read this line from the docs: "Kubectl plugins available via the Krew plugin index are not audited for security." A plugin runs with your kubeconfig.

The checklist before a command in production

  1. kubectl config current-context says the cluster you mean
  2. The command has -n NAMESPACE written out
  3. For a change: kubectl diff shows only what you expect
  4. For a delete: you ran it once with --dry-run=server
  5. For a drain: no --disable-eviction, and a --timeout
  6. For a quick edit on a GitOps-managed object: the same change is on its way to Git
  7. No --force on a StatefulSet pod

FAQ

What is kubectl?

kubectl is the command-line client for the Kubernetes API. Almost every command in this cheat sheet is an HTTP request to the API server of the cluster your current context points to. The kubectl config commands only read and edit your local kubeconfig.

How do I see why a pod is not starting?

Run kubectl describe pod POD and read the Events section at the bottom, or run kubectl events --for pod/POD. For a pod that starts and crashes, run kubectl logs POD --previous.

How do I restart a pod with kubectl?

There is no restart command for a single pod. For a pod that belongs to a Deployment, run kubectl rollout restart deployment/NAME, which replaces every pod gradually. Deleting 1 pod also works, since the Deployment creates a new one.

How do I switch namespace in kubectl?

Add -n NAMESPACE to a command, or change the default of the current context with kubectl config set-context --current --namespace=NAMESPACE.

What is the difference between kubectl apply and kubectl create?

create makes a new object and fails if it exists. apply creates the object or updates it to match the file, and can be run again and again. Use apply for files you keep in Git.

Why does kubectl get all not show my ConfigMaps and Secrets?

all is a category that covers a short list of workload types. ConfigMaps, Secrets, Ingresses and PersistentVolumeClaims are not in it. Use the api-resources one-liner from the section on looking at things.

Which kubectl version should I install?

A version within 1 minor of your cluster's API server. With a 1.36 cluster, kubectl 1.35, 1.36 and 1.37 are supported.

Recap

  • Know your context before every command, and write --context and -n in scripts
  • Debug from the STATUS column: describe for Pending, events for image pulls, logs --previous for crashes
  • kubectl debug replaces exec on images with no shell
  • diff, --dry-run=server, then apply
  • rollout restart to restart, rollout undo to go back, and revert the commit too
  • drain needs --ignore-daemonsets and a timeout, and a PodDisruptionBudget that blocks it is a feature
  • Put --interactive for delete in your kuberc

If you would like someone to look at the cluster behind these commands (yes, that is what we do), claim a free assessment and a senior engineer will review your setup with you.