123DevOps··6 min read

Essential kubectl commands: a practical guide organized by task

The kubectl commands you actually use every day — contexts, inspection, apply, logs, debugging, rollouts, and cleanup — with a quick-reference table and habits that keep you from taking down the wrong cluster.

Kubernetes

kubectl is the front door to any Kubernetes cluster. It has dozens of subcommands and hundreds of flags, but day-to-day work revolves around a small set. This guide organizes those commands by task, from “where am I?” to “how do I undo the deploy that just broke?”

Context and namespace: where am I?

Your kubeconfig stores contexts (cluster + user + default namespace). Before anything else:

kubectl config get-contexts                      # list contexts; * marks the current one
kubectl config current-context
kubectl config use-context prod-sa-east-1        # switch clusters
kubectl config set-context --current --namespace=payments   # default namespace

Setting the namespace on the context saves you from typing -n payments on every command — and from applying things to default by accident.

Listing and inspecting

kubectl get pods                         # current namespace
kubectl get pods -A                      # all namespaces
kubectl get pods -o wide                 # pod IP and node
kubectl get pods -l app=web --show-labels
kubectl get deploy web -o yaml           # full object, as stored in the cluster
kubectl get pods -o jsonpath='{.items[*].spec.nodeName}'
kubectl get pods -w                      # watch changes in real time
kubectl describe pod web-7d9c6b8f5-x2k4p # details + recent events
kubectl explain deployment.spec.strategy # field documentation, right in the terminal

describe usually answers “why won’t the pod start?”: the Events section shows scheduling failures, image pull errors, and probe failures. explain (with --recursive to see the whole tree) saves you trips to the docs.

Creating and applying

kubectl apply -f deploy.yaml             # create or update declaratively
kubectl apply -f k8s/                    # every file in the directory
kubectl apply -k overlays/prod           # built-in Kustomize
kubectl diff -f deploy.yaml              # what would change, before applying
kubectl create deployment web --image=nginx:1.27 --replicas=2 \
  --dry-run=client -o yaml > deploy.yaml # generate a starter manifest

--dry-run=client -o yaml is the fastest way to write YAML without memorizing the structure. In production, prefer versioned manifests applied by a pipeline or GitOps over manual kubectl apply.

Logs

kubectl logs -f deploy/web               # follow logs from one of the deployment's pods
kubectl logs web-7d9c6b8f5-x2k4p --previous   # logs from the container that restarted
kubectl logs web-7d9c6b8f5-x2k4p -c sidecar   # a specific container
kubectl logs -l app=web --all-containers --since=15m --tail=100

--previous is essential for CrashLoopBackOff: the current container was just born, and the cause is in the previous one’s logs.

Exec and debug

kubectl exec -it web-7d9c6b8f5-x2k4p -- sh
kubectl debug -it web-7d9c6b8f5-x2k4p --image=busybox:1.36 --target=web
kubectl debug node/worker-1 -it --image=busybox:1.36

Minimal images (distroless, scratch) have no shell. kubectl debug adds an ephemeral container to the running pod; with --target, it shares the target container’s process namespace, when the runtime supports it. For deeper investigations, see deep infrastructure troubleshooting.

Rollouts and scaling

kubectl set image deploy/web web=nginx:1.27.1
kubectl rollout status deploy/web        # wait for the rollout to finish
kubectl rollout history deploy/web
kubectl rollout undo deploy/web          # go back to the previous revision
kubectl rollout undo deploy/web --to-revision=3
kubectl rollout restart deploy/web       # recreate pods without changing the image
kubectl scale deploy/web --replicas=4

If the deployment has a HorizontalPodAutoscaler, a manual scale will be overwritten by the HPA.

Networking, resources, and events

kubectl port-forward svc/web 8080:80     # reach the Service at localhost:8080
kubectl top nodes                        # requires metrics-server
kubectl top pods --sort-by=memory
kubectl get events --sort-by=.metadata.creationTimestamp
kubectl cp payments/web-7d9c6b8f5-x2k4p:/tmp/dump.txt ./dump.txt   # requires tar in the container
kubectl auth can-i delete pods -n payments

Deleting safely

kubectl delete -f deploy.yaml
kubectl delete pod web-7d9c6b8f5-x2k4p   # the ReplicaSet creates another one
kubectl delete deploy web --dry-run=server   # validate on the server without deleting anything

Don’t make --force --grace-period=0 a habit: it removes the object from the API without waiting for the kubelet’s confirmation, and the container may keep running on the node.

Quick reference

Task Command
See current context kubectl config current-context
Pin a namespace kubectl config set-context --current --namespace=<ns>
List everything kubectl get pods -A -o wide
Why the pod won’t start kubectl describe pod <pod>
Generate YAML kubectl create deployment <name> --image=<img> --dry-run=client -o yaml
Preview changes kubectl diff -f <file>
Logs from the previous crash kubectl logs <pod> --previous
Shell into a minimal image kubectl debug -it <pod> --image=busybox:1.36 --target=<container>
Undo a deploy kubectl rollout undo deploy/<name>
Local access kubectl port-forward svc/<svc> 8080:80

Productivity

alias k=kubectl
source <(kubectl completion bash)        # or: source <(kubectl completion zsh)
complete -o default -F __start_kubectl k # completion for the alias too (bash)
  • kubectx / kubens: switch context and namespace with a short command.
  • k9s: a terminal UI to browse resources, view logs, and open shells.
  • krew: the kubectl plugin manager (kubectl krew install ctx ns neat).

To practice without fear, spin up lightweight Kubernetes on your machine. And to understand what each command triggers behind the scenes, see how Kubernetes works.

Safety first

  • Confirm the context before destructive commands. Show the cluster and namespace in your shell prompt (for example, with kube-ps1) and use different colors for production.
  • Use --dry-run=server: it goes through the API server’s authentication, authorization, and admission without persisting anything.
  • Break the delete --all habit: kubectl delete pods --all in the wrong namespace is an incident. Recent kubectl versions offer kubectl delete --interactive (-i), which asks for confirmation.
  • Separate credentials: distinct kubeconfigs (KUBECONFIG=...) or read-only RBAC for everyday use in production.

Checklist

  • Context and namespace checked before every command that changes the cluster
  • Default namespace set on the context
  • kubectl diff or --dry-run=server before applying changes
  • --previous and describe as first steps for failing pods
  • kubectl debug instead of shipping images with a shell just for debugging
  • Alias, completion, and tools like k9s set up
  • Production access with least-privilege RBAC and the context highlighted in the prompt

The most important kubectl command is the one you run before all the others: kubectl config current-context.

Get updates on new posts and stay in the loop!