DEV Community

DevOps Job Updates
DevOps Job Updates

Posted on Originally published at devopsjobupdates.com

kubectl Cheat Sheet: 100+ Commands for Daily Kubernetes Work

kubectl is the tool you will type more than any other in a Kubernetes job. Every deploy, every debug session, every 3 a.m. incident runs through it. The difference between a fast engineer and a slow one is rarely knowledge of Kubernetes internals. It is fluency: knowing the right command without searching, reading output quickly, and never running a destructive command against the wrong cluster.

This cheat sheet is organised by the job in front of you, not by resource type. When a pod is crashing, you do not want a list of every command that mentions pods. You want the five commands that diagnose a crash, in order. Each section below follows that logic: the commands for one task, what each one does, when to use it, and the mistakes that catch people out. Everything is verified against kubectl v1.37, the current release line as of December 2026, with the latest patch at v1.37.2. The command syntax is stable across recent versions, so these commands also work on 1.36 and 1.35 clusters, but keep your kubectl client within one minor version of the cluster: that is the official version skew policy, and straying further produces warnings and, eventually, real incompatibilities.

Before you copy anything into a terminal, learn the one habit that prevents the most damage in Kubernetes work. Always confirm your context before a command that changes something. A kubectl delete against production when you thought you were on a local cluster is the kind of mistake that ends careers and weekends. The first section of this sheet is about contexts for exactly that reason. Read it first, set up the safety habits, and then use the rest of the sheet freely.

Setup, Contexts and Knowing Where You Are

kubectl talks to clusters through a kubeconfig file, usually at ~/.kube/config. That file lists clusters, users and contexts. A context ties a cluster, a user and a default namespace together, and one context is marked current. Every kubectl command runs against the current context unless you override it with a flag. Understanding that single sentence explains half of all kubectl surprises.

Command What it does When to use it
kubectl version Shows client and server versions First check on any unfamiliar machine; warns when client and server are more than one minor version apart
kubectl version --client Shows only the client version When there is no cluster to talk to, or you only care about the local binary
kubectl cluster-info Shows the API server address and core services Sanity check that you can reach a cluster at all
kubectl config get-contexts Lists every context; a star marks the current one Before any destructive command, and whenever you switch machines
kubectl config current-context Prints the name of the current context The fastest safety check; put it in your shell prompt
kubectl config use-context NAME Switches the current context Moving between staging and production, or between clusters
kubectl config set-context --current --namespace=web Sets the default namespace for the current context When you will spend a session working in one namespace
kubectl config view --minify Shows the current context in detail Debugging authentication or namespace surprises

Two habits make contexts safe. First, put the current context and namespace in your shell prompt. Tools such as kube-ps1 do this for bash and zsh, and once you have it you will wonder how you worked without it. Second, use the --context and --namespace flags for one-off commands instead of switching context.

Install kubectl from the official Kubernetes package repository for your distribution, or download the static binary from dl.k8s.io. The kubectl quick reference in the official Kubernetes documentation is the authoritative companion to this sheet: it lists every command with its flags, and it is the page the CKA exam allows you to consult during the test. Speaking of the exam, if you are preparing for certification, this sheet covers the commands you will need most. The CKA is a two-hour performance-based exam with 15 to 20 practical tasks on live clusters, a 66 percent pass mark, and a current version of Kubernetes v1.37. Our CKA certification guide for 2026 explains the format, domains and study plan in full.

Enable shell completion and set up a short alias. Completion turns kubectl from a memory test into a guided interface, and the alias saves thousands of keystrokes over a year. Keep the full kubectl spelling in runbooks and documentation, and use the alias only interactively.

source <(kubectl completion bash)   # bash; use zsh or fish equivalents
echo 'source <(kubectl completion bash)' >> ~/.bashrc
alias k=kubectl
complete -o default -F __start_kubectl k
Enter fullscreen mode Exit fullscreen mode

Reading State: get, describe and Output Formats

Most kubectl work is reading state. You ask what exists, what state it is in, and what changed. The get command lists resources, and describe explains one resource in human-readable detail. Learn their flags and you will spend far less time guessing.

Command What it does When to use it
kubectl get pods Lists pods in the current namespace Your first look at any namespace
kubectl get pods -A Lists pods in every namespace Finding a pod when you do not know its namespace
kubectl get pods -o wide Adds node, IP and nominated node columns Checking where pods are scheduled and whether IPs look right
kubectl get pods -w Watches pods and updates live Watching a rollout or a pod restarting in real time
kubectl get pods --field-selector=status.phase!=Running Lists only pods that are not running Finding the broken pods without scrolling through healthy ones
kubectl get pods -l app=web Lists pods matching a label Working with one application among many
kubectl get deploy,svc,cm -l app=web Lists several resource types at once Getting the whole picture for one application
kubectl get pod NAME -o yaml Shows the full object as YAML Copying a spec, or seeing fields that describe hides
kubectl get pod NAME -o jsonpath='{.status.podIP}' Prints one field Scripting, or pulling one value out of a large object
kubectl get pods --sort-by=.metadata.creationTimestamp Sorts by age Finding the newest or oldest pods quickly
kubectl describe pod NAME Human-readable summary: status, events, mounts, conditions Diagnosing why a pod is not starting or not ready
kubectl describe deploy -l app=web Describes every matching deployment Checking rollout state and replica counts
kubectl explain pod.spec.containers.resources Shows the documentation for a field Writing YAML when you cannot remember a field name
kubectl api-resources Lists every resource type the cluster knows Discovering custom resources and short names

Output formats deserve a closer look because they change how fast you work. The default table output is for humans. YAML output is for copying and for seeing everything, including the fields you did not know existed. JSONPath output is for scripts and for extracting one value.

kubectl get pods -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName,RESTARTS:.status.containerStatuses[0].restartCount
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
kubectl get svc -o wide
Enter fullscreen mode Exit fullscreen mode

Learn the short names. They are not trivia; they are speed. po for pods, deploy for deployments, svc for services, cm for configmaps, secret for secrets, ns for namespaces, no for nodes, ing for ingress, sts for statefulsets, ds for daemonsets, job for jobs. kubectl get po is the same as kubectl get pods, and after the hundredth time the saved keystrokes add up. The full list is in kubectl api-resources, which also shows the short names for custom resources installed in your cluster.

One more reading habit: use kubectl get events early in any investigation. Events are the cluster's own diary: scheduled, pulled, started, failed, back-off. They expire after about an hour by default, so they are most useful soon after a problem starts.

kubectl get events --sort-by=.lastTimestamp
kubectl get events --types=Warning
kubectl get events -n web --field-selector involvedObject.name=api-7d9f
Enter fullscreen mode Exit fullscreen mode

Creating, Applying and Editing Resources

There are two ways to create resources: imperative commands that do one thing immediately, and declarative files that describe the desired state. Imperative commands are for learning, experimenting and emergencies. Declarative files are for everything that matters. A deployment created with a one-liner cannot be reviewed, versioned or reproduced. The same deployment in a YAML file in Git can be all three.

Command What it does When to use it
kubectl apply -f app.yaml Creates or updates resources from a file Everyday deployments; the default for real work
kubectl apply -f . Applies every file in a directory Deploying a whole application at once
kubectl apply -f https://example.com/app.yaml Applies a manifest from a URL Installing operators and add-ons from upstream
kubectl diff -f app.yaml Shows what would change, without changing anything Before every apply you are unsure about
kubectl create deployment web --image=nginx:1.29 Creates a deployment imperatively Quick experiments and learning
kubectl create namespace web Creates a namespace Setting up a new environment or team space
kubectl create configmap app --from-literal=KEY=VALUE Creates a ConfigMap from a literal Quick configuration for a test
kubectl create secret generic db --from-literal=password=secret Creates a Secret from a literal Seeding a secret by hand; prefer sealed or external secrets in production
kubectl run debug --image=busybox:1.28 -it --rm -- sh Runs a one-off pod and deletes it on exit Network tests and quick checks from inside the cluster
kubectl edit deploy/web Opens a resource in your editor Small urgent fixes; the change is not in Git, so record it
kubectl delete -f app.yaml Deletes everything defined in a file Tearing down an application cleanly
kubectl delete pod NAME --grace-period=0 --force Force-deletes a pod Only for pods stuck terminating; never as a routine

The kubectl diff command is the most underused safety tool in the set. Running kubectl diff -f app.yaml before kubectl apply -f app.yaml shows exactly what will change, in the same way git diff shows what a commit will do. Make it a habit, and make it a team rule. The five seconds it takes have saved more production incidents than any other single habit in this sheet.

When you need a starting manifest, generate one instead of writing it from memory. kubectl create deployment web --image=nginx:1.29 --dry-run=client -o yaml prints the YAML without creating anything, and --dry-run=client -o yaml works with most create commands. Pipe the output to a file and you have a valid starting point that you can edit and commit. This is also the fastest way to learn YAML structure: generate it, read it, change one thing, and see what happens.

Be careful with kubectl edit. It is fast and it feels productive, but the change lives only in the cluster. The next time someone applies the manifest from Git, your edit is overwritten. If you must edit imperatively during an incident, open a pull request to put the change in Git before the incident review.

Logs, Exec and Debugging a Failing Pod

When a pod is failing, work in order: status, events, logs, then a shell inside the container. Skipping ahead to a shell wastes time when the answer was in the events all along. The commands below follow that order.

Command What it does When to use it
kubectl logs POD Shows the current container logs First look at what the application is saying
kubectl logs POD -f Streams logs live Watching behaviour as it happens
kubectl logs POD --previous Shows logs from the previous, crashed container The container that just died holds the answer; this is the single most missed flag in kubectl
kubectl logs POD -c CONTAINER Shows logs for one container in a multi-container pod Sidecar pods, where the default container is not the one you want
kubectl logs -l app=web --tail=50 Shows the last 50 lines for all matching pods Getting a quick sample across replicas
kubectl logs POD --since=10m Shows logs from the last ten minutes Cutting through hours of noise to the recent problem
kubectl exec -it POD -- sh Opens a shell in the container Inspecting files, environment and network from inside
kubectl exec POD -- env Runs one command without an interactive shell Checking environment variables or running a single diagnostic
kubectl debug -it POD --image=busybox:1.28 --target=CONTAINER Adds an ephemeral debug container sharing the pod's namespaces The image has no shell; distroless and minimal images need this
kubectl port-forward svc/api 8080:80 Forwards a local port to a service Testing a service from your laptop without exposing it
kubectl port-forward pod/POD 8080:80 Forwards a local port to one pod Testing a single replica in isolation
kubectl cp POD:/path/file ./file Copies a file out of a container Retrieving a config file or a crash dump for inspection

The --previous flag deserves emphasis because it is the difference between solving a crash and staring at an empty log. When a container crashes and restarts, kubectl logs shows the new container, which has just started and has nothing interesting to say. The old container, the one that actually failed, is only reachable with --previous. If you remember one flag from this whole sheet, remember that one.

When the image has no shell, kubectl debug is the answer. Distroless images are popular precisely because they contain no shell and no package manager, which makes them smaller and harder to attack, but it also means kubectl exec fails. The debug command attaches an ephemeral container with the tools you need, sharing the target container's process namespace so you can inspect it. The ephemeral container disappears when you exit, and it requires a cluster that supports ephemeral containers, which all recent versions do.

A reliable debugging sequence for a pod stuck in CrashLoopBackOff looks like this. First, kubectl describe pod and read the events at the bottom: they often name the cause directly, such as a failed image pull or a missing ConfigMap. Then kubectl logs POD --previous to read the crash output. Then check the pod's resource requests against the node's available capacity, and check whether a liveness probe is killing a slow-starting container. Most crashes are one of these causes, and the sequence finds them in minutes.

Rollouts, Scaling and Rollbacks

Deployments exist so that updates are boring. The rollout commands let you watch an update, pause it, and roll it back when it goes wrong, all without touching YAML.

Command What it does When to use it
kubectl rollout status deployment/web Waits and reports until the rollout finishes or fails After every apply; add it to your deploy scripts
kubectl rollout history deployment/web Lists past revisions Finding which revision is live and what came before
kubectl rollout history deployment/web --revision=3 Shows the details of one revision Checking what changed in a specific release
kubectl rollout undo deployment/web Rolls back to the previous revision The new version is broken; get the old one back now
kubectl rollout undo deployment/web --to-revision=2 Rolls back to a specific revision The previous revision was also bad; go further back
kubectl rollout restart deployment/web Restarts all pods gradually Picking up a changed ConfigMap or Secret, or clearing a stuck state
kubectl rollout pause deployment/web Pauses a rollout mid-flight Canary style: stop at one replica and check before continuing
kubectl rollout resume deployment/web Resumes a paused rollout The canary looks good; let the rollout finish
kubectl set image deployment/web app=img:1.1 Changes the image of one container Quick image update without editing a file
kubectl scale deployment/web --replicas=5 Sets the replica count Manual scaling for a traffic spike or a quiet period
kubectl autoscale deployment/web --min=2 --max=10 --cpu-percent=70 Creates a HorizontalPodAutoscaler Letting the cluster scale on CPU automatically
kubectl get hpa Shows autoscaler status Checking whether scaling is keeping up with demand

Two rollout facts save real incidents. First, kubectl rollout undo is fast because the old ReplicaSet still exists with its old pods ready to scale back up. It is not a redeploy; it is a switch back to something that already ran. Second, a rollout that is stuck usually means the new pods never became ready, which usually means a readiness probe is failing or the image cannot be pulled. If you are learning how deployments are written, our Kubernetes Deployment YAML tutorial walks through a complete manifest field by field.

Be careful with kubectl rollout restart. It is tempting to use it as a fix for everything, because restarting pods often makes a symptom disappear. But it also destroys the evidence: the logs of the old pods are gone unless you captured them, and the underlying cause is still there. Restart to recover service, then investigate the cause.

Nodes, Namespaces and Cluster Administration

Nodes are where pods run, and namespaces are how teams share a cluster without stepping on each other. The commands in this section are the ones cluster administrators and on-call engineers reach for when the problem is bigger than one pod.

Command What it does When to use it
kubectl get nodes Lists nodes and their status First check when pods cannot be scheduled
kubectl get nodes -o wide Adds addresses, OS and container runtime Checking node versions and network details
kubectl describe node NODE Shows capacity, allocatable resources and conditions Working out whether a node is full or unhealthy
kubectl top nodes Shows live CPU and memory per node Finding the hot node; requires metrics-server
kubectl top pods -A Shows live CPU and memory per pod Finding the pod eating all the memory
kubectl cordon NODE Marks a node unschedulable Preparing a node for maintenance without killing anything
kubectl drain NODE --ignore-daemonsets --delete-emptydir-data Evicts pods from a node safely Removing a node for maintenance or replacement
kubectl uncordon NODE Marks a node schedulable again After maintenance is finished
kubectl get namespaces Lists namespaces Seeing how the cluster is divided up
kubectl get all -n web Lists the common resources in a namespace A quick inventory; note it does not show every resource type
kubectl delete namespace web Deletes a namespace and everything in it Only when you are certain; this is not undoable
kubectl get pods -A --field-selector spec.nodeName=NODE Lists every pod on one node Seeing what will be affected before draining a node

Always cordon before you drain, and always check what is on the node first. Draining evicts pods, and pods with local emptyDir data or without a controller to recreate them will be lost unless you pass the right flags. The drain command will refuse to proceed when it would strand a pod, which is a safety feature, not an annoyance.

kubectl get all is a useful shortcut with a trap: it shows pods, services, deployments, ReplicaSets and a few other common types, but not ConfigMaps, Secrets, Ingresses or custom resources. A namespace can look empty under get all while still holding the ConfigMap your application needs. For a real inventory, list the specific types or use kubectl api-resources to see what exists in your cluster.

Permissions, Output Tricks and Daily Habits

RBAC decides what you are allowed to do, and the fastest way to understand a permission error is to ask the cluster before you try the action. The auth can-i command does exactly that.

Command What it does When to use it
kubectl auth can-i delete pods Checks whether you can delete pods in the current namespace Before a command that might fail on permissions
kubectl auth can-i create deployments -n web Checks a permission in a specific namespace Confirming access before a deploy to a new namespace
kubectl auth can-i '*' '*' --all-namespaces Checks whether you are effectively a cluster admin Understanding how much power your account has
kubectl auth whoami Shows who you are authenticated as Debugging identity surprises on shared machines
kubectl get roles,rolebindings -n web Lists RBAC roles and bindings Working out who can do what in a namespace
kubectl get clusterroles,clusterrolebindings Lists cluster-wide RBAC Auditing broad permissions
kubectl wait --for=condition=Ready pod -l app=web --timeout=120s Blocks until pods are ready or the timeout hits Scripts that must not proceed until the app is up
`kubectl get pods -A -o json \ jq -r '.items[].metadata.name'` Pipes full JSON into jq for processing
kubectl proxy Starts a local proxy to the API server Exploring the API from a browser or curl on localhost
`kubectl get pods -A --no-headers \ wc -l` Counts all pods in the cluster

A few habits tie the whole sheet together. Keep kubectl within one minor version of your clusters, and upgrade the client when the cluster upgrades. Use kubectl diff before every apply you are unsure about. Put the context in your prompt. Use --previous for crashed containers. And never run a delete against a context you have not just verified. These five habits prevent the large majority of kubectl accidents, and they cost nothing.

The official kubectl reference documents every command and flag in full, including the ones this sheet skips, such as certificate management, node debugging and the plugin system. When you need a flag this sheet does not list, that reference is the first place to look, and kubectl COMMAND --help is the fastest way to see it in the terminal.

Frequently Asked Questions

How do I switch between clusters with kubectl?

Use contexts. kubectl config get-contexts lists them, kubectl config use-context NAME switches the current one, and kubectl --context NAME get pods runs a single command against another cluster without switching. Put the current context in your shell prompt so you always know where you are.

Why does kubectl say my pod is in CrashLoopBackOff?

The container starts, fails, and Kubernetes restarts it with increasing delays. Run kubectl describe pod for the events, then kubectl logs POD --previous to read the output of the container that crashed. The common causes are a bad image, a missing ConfigMap or Secret, a failed readiness probe, or the application itself exiting on startup.

What is the difference between kubectl apply and kubectl create?

Create makes a new resource and fails if it already exists. Apply creates it if it is missing and updates it if it exists, based on the file you pass. Apply is the right default for real work because it is repeatable: you can run the same command ten times and get the same result. Create is for one-off experiments.

Can I use kubectl without a cluster?

Mostly no. kubectl is a client for the Kubernetes API, so it needs a cluster to talk to. You can run kubectl version --client and generate YAML with --dry-run=client without a cluster, and for learning you can run a local cluster with kind or minikube on your laptop, which gives you a real API server to practise against.

How do I prepare for the CKA exam with kubectl?

Practise the commands in this sheet until they are muscle memory, especially get, describe, logs, exec, apply, diff, rollout and drain. The CKA is a two-hour performance-based exam with 15 to 20 tasks, a 66 percent pass mark, and Kubernetes v1.37 as the current version. Speed matters as much as knowledge: you have roughly six to eight minutes per task, so practise under time pressure and learn to use the official documentation quickly.

Conclusion

kubectl rewards fluency more than almost any other tool in DevOps. The commands in this sheet are the ones working engineers type every day, and the habits around them, verifying context, diffing before applying, reading logs from the previous container, are what separate a smooth shift from a painful one. Keep this sheet open in a second tab, practise the debugging sequence until it is automatic, and build a local cluster with kind or minikube so you can try the destructive commands safely. If you are still learning the basics, our Kubernetes tutorial for beginners covers pod lifecycle and common failure states from first principles.

Sources: Verified 2 Dec 2026. kubectl quick reference: https://kubernetes.io/docs/reference/kubectl/quick-reference/ ; kubectl reference: https://kubernetes.io/docs/reference/kubectl/ . kubectl v1.37.2 latest stable; version skew policy within one minor version. CKA format (2 hours, 15–20 tasks, 66%, v1.37) cross-checked against Linux Foundation summaries; exam price not stated — re-check on the Linux Foundation CKA page before booking.

Top comments (0)