# kubectl Cheat Sheet: 30+ Essential Commands

- URL: https://karandeepsingh.ca/posts/kubectl-cheat-sheet/
- Author: Karandeep Singh
- Published: 2026-06-18
- Series: Kubernetes and Containers
- Tags: kubernetes, cli, containers
- Summary: The kubectl commands you actually reach for, grouped by task — inspecting pods, managing deployments and services, reading logs, and debugging — with copy-paste examples and notes on when to use each.

`kubectl` is the command-line tool you use to talk to a Kubernetes cluster, and it has hundreds of flags. This kubectl cheat sheet skips the exhaustive man page and collects the 30+ commands you actually reach for day to day, grouped by the task you are trying to accomplish.

Every command here is copy-paste ready. Bookmark this kubectl cheat sheet, then come back when you need to inspect a pod, ship a deployment, read logs, or debug a workload that refuses to start. Each section explains what the command does and when to use it, so it doubles as a quick reference and a learning path.

![kubectl cheat sheet — terminal commands for Kubernetes pods, deployments, and services](https://karandeepsingh.ca/images/posts/kubectl-cheat-sheet-card.jpg)

## How kubectl Talks to Your Cluster

Before the commands, it helps to know what happens when you press Enter. `kubectl` is a client. It reads your kubeconfig file (`~/.kube/config`), builds an HTTPS request, and sends it to the cluster's **API server**. The API server authenticates you, validates the request, and persists the desired state to `etcd`. Controllers and the scheduler then make the real world match that state.

```mermaid
graph LR
  A[kubectl] -->|HTTPS + kubeconfig| B[kube-apiserver]
  B --> C[(etcd)]
  B --> D[Scheduler]
  B --> E[Controllers]
  E --> F[kubelet on Node]
  F --> G[Pods / Containers]
```

That mental model explains a lot of behavior: `kubectl apply` only records *desired* state, while the actual rollout happens asynchronously. It is why you run `kubectl rollout status` afterward to wait for reality to catch up.

## Cluster Info and Context

Start every session by confirming **which cluster** you are pointed at. Running the right command against the wrong cluster is the most common (and most dangerous) kubectl mistake.

```bash
kubectl version                    # client + server versions
kubectl cluster-info               # API server and core service URLs
kubectl config get-contexts        # list all configured clusters
kubectl config current-context     # which cluster am I on right now?
kubectl config use-context prod    # switch clusters
kubectl get nodes -o wide          # nodes, internal IPs, OS, kernel
```

**warning:**
`kubectl config use-context` changes your **default** cluster for every subsequent command. On shared machines, prefer `--context=NAME` per command so you never accidentally run a destructive command against production.

## Inspect Pods with kubectl

Pods are where your containers run, so most debugging starts here. `get` shows you the list, `describe` shows you the details and recent events.

```bash
kubectl get pods                          # pods in the current namespace
kubectl get pods -A                       # pods in ALL namespaces
kubectl get pods -n kube-system           # pods in a specific namespace
kubectl get pods -o wide                  # add node and pod IP columns
kubectl get pods -l app=api               # filter by label
kubectl get pods --watch                  # stream status changes live
kubectl describe pod api-7d9f-xyz         # events, conditions, restarts
```

The `STATUS` and `RESTARTS` columns tell the story. A high restart count usually means a crash loop, and `kubectl describe` will show the reason near the bottom under **Events**.

## Manage Deployments and Rollouts

Most workloads are managed by a Deployment, not a bare pod. These kubectl commands cover the full lifecycle — ship, watch, scale, and roll back.

```bash
kubectl get deploy                                  # list deployments
kubectl rollout status deploy/api                   # wait for a rollout to finish
kubectl set image deploy/api app=myapp:v2           # update the image (triggers a rollout)
kubectl scale deploy/api --replicas=5               # scale up or down
kubectl rollout history deploy/api                  # list previous revisions
kubectl rollout undo deploy/api                     # roll back to the previous version
kubectl rollout restart deploy/api                  # restart pods (e.g. to pick up a new Secret)
```

**tip:**
`kubectl rollout restart` is the clean way to recycle pods after changing a ConfigMap or Secret — no need to delete pods by hand or bump a fake annotation.

## Services, Networking, and Port-Forwarding

A Service gives your pods a stable address. When you need to reach a workload from your laptop without exposing it publicly, `port-forward` is your friend.

```bash
kubectl get svc                                     # list services + cluster IPs
kubectl expose deploy/api --port=80 --target-port=8080   # create a Service for a Deployment
kubectl port-forward svc/api 8080:80                # tunnel localhost:8080 to the Service
kubectl get endpoints api                           # which pods is the Service actually routing to?
```

If a Service returns nothing, check `kubectl get endpoints`. Empty endpoints almost always mean the Service's label selector does not match your pods.

## ConfigMaps, Secrets, and Resource Files

Kubernetes is declarative. The commands below create config imperatively for quick tests, but the `apply` workflow is what you should use in real pipelines.

```bash
kubectl create configmap app-config --from-literal=LOG_LEVEL=debug
kubectl create secret generic db-creds --from-literal=password=s3cr3t
kubectl get secret db-creds -o jsonpath='{.data.password}' | base64 -d   # decode a Secret value
kubectl apply -f deployment.yaml                    # create OR update from a file (declarative)
kubectl apply -f ./k8s/                             # apply every manifest in a directory
kubectl diff -f deployment.yaml                     # preview what apply would change
kubectl delete -f deployment.yaml                   # delete the resources defined in a file
```

The difference between `apply` and `create` is the most important concept on this whole kubectl cheat sheet: `apply` is **idempotent**. Run it ten times and you converge on the same state, which is exactly what CI/CD and GitOps need.

## kubectl Logs and Live Debugging

When a workload misbehaves, these four commands solve 90% of incidents.

```bash
kubectl logs api-7d9f-xyz                           # print a pod's logs
kubectl logs -f api-7d9f-xyz                        # follow the logs live (tail -f)
kubectl logs api-7d9f-xyz --previous                # logs from the PREVIOUS crashed container
kubectl logs deploy/api --tail=100 --since=15m      # last 100 lines from the last 15 minutes
kubectl exec -it api-7d9f-xyz -- /bin/sh            # open a shell inside the container
kubectl get events --sort-by=.lastTimestamp        # cluster events, newest last
```

**info:**
`kubectl logs --previous` is the single most useful debugging flag in this cheat sheet. When a pod is stuck in [`CrashLoopBackOff`](https://karandeepsingh.ca/posts/fix-kubernetes-crashloopbackoff/), the current container has no logs yet — the *previous* one holds the stack trace that explains why it died.

## Namespaces and Resource Usage

Namespaces partition a cluster. Setting a default namespace saves you from typing `-n` on every command.

```bash
kubectl get ns                                                  # list namespaces
kubectl config set-context --current --namespace=staging        # set default namespace
kubectl top nodes                                               # CPU/memory per node
kubectl top pods -A                                             # CPU/memory per pod (needs metrics-server)
kubectl api-resources                                           # every resource type + its short name
kubectl explain pod.spec.containers                             # built-in docs for any field
```

## kubectl Productivity Tips

A few one-time setups make every future session faster. These are the quality-of-life tweaks that separate a fluent operator from someone fighting the CLI.

```bash
alias k=kubectl                                     # type k instead of kubectl
source <(kubectl completion bash)                   # tab-completion (use 'zsh' for zsh)
kubectl run tmp --image=nginx --dry-run=client -o yaml   # generate a manifest without applying it
kubectl get pods -o jsonpath='{.items[*].metadata.name}' # script-friendly output
```

**Bonus: a kubectl alias that auto-completes too**
If you alias `kubectl` to `k`, tab-completion stops working for the alias. Add this after the completion line to fix it on bash:

```bash
complete -o default -F __start_kubectl k
```
Now `k get po<TAB>` completes just like the full command.

## Common kubectl Pitfalls (and Fixes)

Even with a cheat sheet in hand, a few traps catch almost everyone:

- **Running against the wrong cluster.** Always check `kubectl config current-context` first, and prefer `--context` for one-off production commands.
- **`kubectl edit` changes vanish.** Edits to a resource managed by `apply` get reverted on the next deploy. Change the source manifest, not the live object.
- **`top` returns an error.** `kubectl top` needs the [metrics-server](https://github.com/kubernetes-sigs/metrics-server) add-on installed; it is not part of a vanilla cluster.
- **Empty Service endpoints.** A Service with no endpoints means its label selector does not match any running pods — compare the selector to your pod labels.
- **Deleting pods to "restart" them.** For a Deployment, use `kubectl rollout restart`; deleting pods is recreated chaos, not a controlled restart.

If the objects themselves are still new, start with [Kubernetes fundamentals: pods, deployments, and services](https://karandeepsingh.ca/posts/kubernetes-fundamentals-pods-deployments-services/). To spin up a real cluster to practice on, follow [EKS setup with eksctl](https://karandeepsingh.ca/posts/kubernetes-eks-setup-eksctl/), and for what is actually running inside each pod, [containers from scratch in Go](https://karandeepsingh.ca/posts/containers-from-scratch-go/) builds the primitives by hand.

## Suggested Learning Path

1. Practice `get`, `describe`, and `logs` on a throwaway `minikube` or `kind` cluster until they are muscle memory.
2. Move from imperative `create` to declarative `apply -f` with version-controlled manifests.
3. Learn `rollout status`, `undo`, and `diff` so deployments stop being scary.
4. Add `jsonpath` and `--dry-run=client -o yaml` once you start scripting and templating.

Master those four steps and this kubectl cheat sheet stops being a reference you look up and becomes the workflow you run on autopilot.

**Question:** Which kubectl command do you run most often when debugging a failing pod?

## References and Further Reading

- Kubernetes Authors. [kubectl Quick Reference](https://kubernetes.io/docs/reference/kubectl/quick-reference/). Kubernetes Documentation.
- Kubernetes Authors. [Command line tool (kubectl)](https://kubernetes.io/docs/reference/kubectl/). Kubernetes Documentation.
- Kubernetes Authors. [Debug Running Pods](https://kubernetes.io/docs/tasks/debug/debug-application/debug-running-pod/). Kubernetes Documentation.
- Burns, B., Beda, J., Hightower, K., & Evenson, L. (2022). [Kubernetes: Up and Running, 3rd Edition](https://www.oreilly.com/library/view/kubernetes-up-and/9781098110192/). O'Reilly Media.

## Quiz

1. Which kubectl command streams a pod's logs live as they are written?
   a) kubectl get pod NAME
   b) kubectl describe pod NAME
   c) kubectl logs -f NAME
   d) kubectl exec NAME
   Answer: c. `kubectl logs -f NAME` follows the log stream (like `tail -f`). `get` and `describe` show state, not log output, and `exec` runs a command inside the container.

2. How do you list pods across every namespace in the cluster?
   a) kubectl get pods
   b) kubectl get pods -A
   c) kubectl get pods --wide
   d) kubectl get all
   Answer: b. `kubectl get pods -A` (short for `--all-namespaces`) lists pods in every namespace. Plain `kubectl get pods` only shows the current namespace.

3. Which command safely rolls a Deployment back to its previous version?
   a) kubectl delete deploy/NAME
   b) kubectl rollout undo deploy/NAME
   c) kubectl scale deploy/NAME --replicas=0
   d) kubectl apply -f old.yaml
   Answer: b. `kubectl rollout undo deploy/NAME` reverts to the previous rollout revision without downtime. Deleting or scaling to zero takes the app offline.

4. What makes `kubectl apply -f` different from `kubectl create -f`?
   a) apply is faster
   b) apply works only on pods
   c) apply is declarative and updates existing resources
   d) apply deletes the resource first
   Answer: c. `apply` is declarative and idempotent — it creates the resource if missing and updates it in place if it already exists, which is why it is the standard for GitOps and CI/CD.


