# kubectl cheatsheet: essential commands for Kubernetes

LLMS index: [llms.txt](/en/llms.txt)

---

kubectl is the primary interface to a Kubernetes cluster. This cheatheet covers routine operations — from context setup to pod debugging and namespace switching. All commands are verified against current kubectl versions (1.28+).

## Installation and Context Setup

Installation depends on your OS. On Linux, use the package manager or the binary directly:

```bash
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
chmod +x kubectl && sudo mv kubectl /usr/local/bin/
kubectl version --client
```

Configuration lives in `~/.kube/config`. A context defines the cluster, user, and default namespace.

```bash
kubectl config current-context
kubectl config use-context production-cluster
kubectl config view --minify   # show current context
kubectl config get-contexts    # list all contexts
```

> [!TIP]
> If you work with multiple clusters, store configs in the `KUBECONFIG` variable separated by colons: `export KUBECONFIG=~/.kube/config:~/.kube/prod-config`.

## Working with Pods

Basic operations:

```bash
kubectl get pods                          # all pods in the current namespace
kubectl get pods -A                       # all namespaces
kubectl describe pod <pod-name>           # details and events
kubectl logs <pod-name>                   # container logs
kubectl logs <pod-name> -c <container>    # logs for a specific container in a multi-container pod
kubectl exec -it <pod-name> -- /bin/sh    # enter a pod
kubectl delete pod <pod-name>             # delete a pod
```

## Deployments, StatefulSets, and DaemonSets

```bash
kubectl get deployments,statefulsets,daemonsets
kubectl rollout status deployment/<name>       # update status
kubectl rollout history deployment/<name>      # revision history
kubectl rollout undo deployment/<name>         # rollback to previous revision
kubectl rollout undo deployment/<name> --to-revision=2   # rollback to a specific revision
kubectl scale deployment/<name> --replicas=5   # scale replicas
```

For StatefulSets, startup order and stable identities are critical. For DaemonSets, a guaranteed instance runs on every node.

> [!WARNING]
> Do not run `kubectl delete` on a Deployment without checking `kubectl get deployment` first. Deleting the controller does not automatically remove pods — they will be recreated unless you use `--cascade=orphan` (in older versions) or delete through `kubectl delete deployment`.

## Services, Ingress, and ConfigMap

```bash
kubectl get svc                      # services
kubectl expose deployment/<name> --port=80 --type=NodePort   # create svc from a deployment
kubectl get ingress                  # ingress resources
kubectl describe ingress <name>      # rules and events
kubectl apply -f ingress.yaml        # apply ingress from a file
```

ConfigMap and Secret for configuration:

```bash
kubectl create configmap app-config --from-file=config.yaml
kubectl get configmap app-config -o yaml
kubectl create secret generic db-creds --from-literal=password='s3cr3t'
kubectl get secret db-creds -o jsonpath='{.data.password}' | base64 -d
```

## Debugging and Diagnostics

When a pod is not working, follow this sequence:

```bash
kubectl get pods -o wide             # status and node
kubectl describe pod <pod-name>      # events, reason for CrashLoopBackOff
kubectl logs <pod-name> --previous   # logs from a crashed container
kubectl top pod <pod-name>           # CPU/memory consumption (requires metrics-server)
kubectl attach -it <pod-name> -- /bin/sh   # alternative to exec
```

To test network connectivity from inside the cluster:

```bash
kubectl run debug-pod --image=busybox --rm -it --restart=Never -- wget -O- http://<svc-name>.<namespace>.svc.cluster.local:80
```

> [!NOTE]
> If `kubectl top` returns an error, metrics-server is not installed. Installation depends on your provider: `kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml`.

## Labels, Selectors, and Output Formatting

Labels let you group resources and select them in bulk:

```bash
kubectl get pods --show-labels
kubectl label pods <pod-name> app=frontend tier=web
kubectl get pods -l app=frontend       # label selector
kubectl get pods -l 'app in (frontend,backend)'
kubectl get pods -l '!tier=web'        # negative selector
```

Output formatting:

```bash
kubectl get pods -o wide
kubectl get pods -o json               # full JSON
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase
```

| Flag | Description |
|------|-------------|
| `-n, --namespace` | Specify namespace |
| `-o, --output` | Format: `json`, `yaml`, `wide`, `custom-columns` |
| `-l, --selector` | Label selector |
| `-f, --filename` | Configuration file (YAML/JSON) |
| `--show-labels` | Show labels column |
| `-w, --watch` | Streaming update mode |
| `--all-namespaces, -A` | All namespaces |

## Managing Namespaces and Switching Contexts

```bash
kubectl get namespace
kubectl create namespace staging
kubectl delete namespace staging        # deletion is asynchronous
kubectl config set-context --current --namespace=staging   # default namespace in context
```

For convenience, create a shell alias or function:

```bash
# ~/.bashrc or ~/.zshrc
kswitch() { kubectl config use-context "$1" && kubectl config set-context --current --namespace="$2"; }
# usage: kswitch production-cluster default
```

> [!TIP]
> `kubectl config rename-context`, `kubectl config unset`, and `kubectl config set` let you edit the config without manually editing YAML. Verify the result with `kubectl config view`.

kubectl is more than a CLI — it is an abstraction layer over the Kubernetes API. Knowing formatting flags and selectors cuts diagnostic time significantly. Keep this cheatheet handy and update it as new versions ship.
