man kubectl

Kubernetes Cheatsheet

The kubectl commands I reach for every day: inspect clusters, run and debug workloads, wire up networking, storage and config. Every command has a real example you can copy.

Showing 83 of 83 commands

Cluster Info

10 commands

Check cluster health, contexts, nodes and client configuration.

kubectl version --client beginner Show the installed kubectl version without contacting the cluster.

Example

bash
kubectl version --client
Client Version: v1.34.1
Kustomize Version: v5.7.1

Tip: Keep kubectl within one minor version of the API server. Drop --client to see both versions.

kubectl cluster-info beginner Print the control plane and core service endpoints.

Example

bash
kubectl cluster-info
Kubernetes control plane is running at https://10.0.0.10:6443
CoreDNS is running at https://10.0.0.10:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

Tip: Run this first after configuring a new kubeconfig: it proves the endpoint and credentials work.

kubectl get nodes beginner List the nodes with their status, roles, age and kubelet version.

Example

bash
kubectl get nodes
NAME            STATUS   ROLES           AGE   VERSION
control-plane   Ready    control-plane   42d   v1.34.1
worker-1        Ready    <none>          42d   v1.34.1
worker-2        Ready    <none>          42d   v1.34.1
kubectl get nodes -o wide beginner Add internal IPs, OS image, kernel and container runtime to the node list.

Example

bash
kubectl get nodes -o wide
NAME       STATUS   ROLES    AGE   VERSION   INTERNAL-IP   OS-IMAGE             KERNEL-VERSION     CONTAINER-RUNTIME
worker-1   Ready    <none>   42d   v1.34.1   10.0.1.21     Ubuntu 24.04.1 LTS   6.8.0-48-generic   containerd://1.7.22
worker-2   Ready    <none>   42d   v1.34.1   10.0.1.22     Ubuntu 24.04.1 LTS   6.8.0-48-generic   containerd://1.7.22
kubectl describe node <name> intermediate Show capacity, conditions, labels, taints and the pods scheduled on a node.

Example

bash
kubectl describe node worker-1 | grep -A 6 'Allocated resources'
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource           Requests     Limits
  --------           --------     ------
  cpu                1850m (46%)  4 (100%)
  memory             3172Mi (40%) 6Gi (78%)

Tip: When pods stay Pending, compare Requests here with the node capacity: the scheduler uses requests, not real usage.

kubectl top nodes intermediate Show live CPU and memory usage per node.

Example

bash
kubectl top nodes
NAME       CPU(cores)   CPU(%)   MEMORY(bytes)   MEMORY(%)
worker-1   612m         15%      4120Mi          52%
worker-2   388m         9%       2875Mi          36%

Tip: Needs metrics-server installed in the cluster; without it you get "Metrics API not available".

kubectl config get-contexts beginner List every context in your kubeconfig; the current one is marked with *.

Example

bash
kubectl config get-contexts
CURRENT   NAME            CLUSTER         AUTHINFO        NAMESPACE
*         prod-cluster    prod-cluster    prod-admin      default
          staging         staging         staging-admin   web
kubectl config use-context <name> beginner Switch kubectl to another cluster or user.

Example

bash
kubectl config use-context staging
Switched to context "staging".

Tip: Show the current context in your shell prompt so you never run a command against prod by accident.

kubectl config current-context beginner Print only the name of the active context. Handy in scripts.

Example

bash
kubectl config current-context
prod-cluster
kubectl api-resources intermediate List every resource type the API server knows, with short names and API groups.

Example

bash
kubectl api-resources --api-group=apps
NAME                  SHORTNAMES   APIVERSION   NAMESPACED   KIND
controllerrevisions                apps/v1      true         ControllerRevision
daemonsets            ds           apps/v1      true         DaemonSet
deployments           deploy       apps/v1      true         Deployment
replicasets           rs           apps/v1      true         ReplicaSet
statefulsets          sts          apps/v1      true         StatefulSet

Tip: The SHORTNAMES column is why you can type kubectl get deploy instead of deployments.

Pods

13 commands

List, inspect, run, log and connect to pods.

kubectl get pods beginner List the pods in the current namespace.

Example

bash
kubectl get pods
NAME                   READY   STATUS    RESTARTS   AGE
web-7d4b9c8f6-x2kqp    1/1     Running   0          3h
web-7d4b9c8f6-zt8wm    1/1     Running   0          3h
worker-5f6c7d9b-9pl2d  1/1     Running   2          1d
kubectl get pods -A beginner List pods in every namespace (short for --all-namespaces).

Example

bash
kubectl get pods -A | head -4
NAMESPACE     NAME                              READY   STATUS    RESTARTS   AGE
default       web-7d4b9c8f6-x2kqp               1/1     Running   0          3h
kube-system   coredns-7c65d6cfc9-4vx8b          1/1     Running   0          42d
kube-system   metrics-server-6d94bc8694-m2r7z   1/1     Running   0          42d
kubectl get pods -o wide beginner Add the pod IP and the node each pod runs on.

Example

bash
kubectl get pods -o wide
NAME                  READY   STATUS    RESTARTS   AGE   IP            NODE       NOMINATED NODE   READINESS GATES
web-7d4b9c8f6-x2kqp   1/1     Running   0          3h    10.244.1.14   worker-1   <none>           <none>
web-7d4b9c8f6-zt8wm   1/1     Running   0          3h    10.244.2.9    worker-2   <none>           <none>
kubectl get pods -l <selector> beginner Filter pods by label, exactly like a Service or Deployment selector does.

Example

bash
kubectl get pods -l app=web,tier=frontend
NAME                  READY   STATUS    RESTARTS   AGE
web-7d4b9c8f6-x2kqp   1/1     Running   0          3h
web-7d4b9c8f6-zt8wm   1/1     Running   0          3h

Tip: Add --show-labels to any get command to see which labels you can filter on.

kubectl describe pod <name> beginner Show a pod's containers, probes, volumes, conditions and recent events.

Example

bash
kubectl describe pod web-7d4b9c8f6-x2kqp | tail -6
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  3h    default-scheduler  Successfully assigned default/web-7d4b9c8f6-x2kqp to worker-1
  Normal  Pulled     3h    kubelet            Container image "nginx:1.27" already present on machine
  Normal  Started    3h    kubelet            Started container nginx

Tip: The Events section at the bottom explains most Pending, ImagePullBackOff and CrashLoopBackOff problems.

kubectl logs <pod> beginner Print the logs of a pod's (first) container.

Example

bash
kubectl logs web-7d4b9c8f6-x2kqp --tail=3
10.244.0.1 - - [28/Oct/2026:13:02:11 +0000] "GET /healthz HTTP/1.1" 200 2 "-" "kube-probe/1.34"
10.244.0.1 - - [28/Oct/2026:13:02:21 +0000] "GET /healthz HTTP/1.1" 200 2 "-" "kube-probe/1.34"
10.244.2.5 - - [28/Oct/2026:13:02:24 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/8.10.1"
kubectl logs -f <pod> -c <container> intermediate Stream logs live from one container of a multi-container pod.

Example

bash
kubectl logs -f web-7d4b9c8f6-x2kqp -c nginx --since=10m
10.244.2.5 - - [28/Oct/2026:13:05:02 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/8.10.1"
^C

Tip: Press Ctrl+C to stop following. --since=10m skips old noise.

kubectl logs --previous <pod> intermediate Read the logs of the container instance that crashed before the current restart.

Example

bash
kubectl logs worker-5f6c7d9b-9pl2d --previous
Connecting to redis://redis:6379 ...
panic: dial tcp 10.96.14.7:6379: connect: connection refused

Tip: Essential for CrashLoopBackOff: the current container often has no useful logs yet.

kubectl exec -it <pod> -- <command> intermediate Open an interactive shell (or run any command) inside a running container.

Example

bash
kubectl exec -it web-7d4b9c8f6-x2kqp -- sh -c 'hostname && nginx -v'
web-7d4b9c8f6-x2kqp
nginx version: nginx/1.27.2

Tip: Use -- before the command so kubectl does not parse its flags. Distroless images have no shell: use kubectl debug instead.

kubectl run <name> --image=<image> beginner Start a single pod from an image. Great for quick tests.

Example

bash
kubectl run nginx --image=nginx:1.27 --restart=Never --port=80
pod/nginx created

Tip: Pods created this way are not recreated if they die. Use a Deployment for anything that must stay up.

kubectl port-forward pod/<name> <local>:<remote> intermediate Tunnel a local port to a port on a pod, without exposing it.

Example

bash
kubectl port-forward pod/web-7d4b9c8f6-x2kqp 8080:80
Forwarding from 127.0.0.1:8080 -> 80
Forwarding from [::1]:8080 -> 80
Handling connection for 8080
kubectl cp <pod>:<path> <local-path> intermediate Copy files between a container and your machine (both directions).

Example

bash
kubectl cp web-7d4b9c8f6-x2kqp:/etc/nginx/nginx.conf ./nginx.conf
tar: Removing leading `/' from member names

Tip: kubectl cp needs tar inside the container. The tar warning above is harmless.

kubectl delete pod <name> beginner Delete a pod. If a controller owns it, a replacement is created right away.

Example

bash
kubectl delete pod web-7d4b9c8f6-x2kqp
pod "web-7d4b9c8f6-x2kqp" deleted

Tip: Prefer kubectl rollout restart for a Deployment: it replaces pods gradually instead of one by one by hand.

Deployments

12 commands

Create, scale, update and roll back Deployments.

kubectl create deployment <name> --image=<image> beginner Create a Deployment imperatively.

Example

bash
kubectl create deployment web --image=nginx:1.27 --replicas=3
deployment.apps/web created
kubectl get deployments beginner List Deployments with ready, up-to-date and available replicas.

Example

bash
kubectl get deploy
NAME     READY   UP-TO-DATE   AVAILABLE   AGE
web      3/3     3            3           3h
worker   1/1     1            1           1d
kubectl describe deployment <name> beginner Show the strategy, pod template, conditions and rollout events.

Example

bash
kubectl describe deployment web | grep -E 'Replicas|StrategyType|Image'
Replicas:               3 desired | 3 updated | 3 total | 3 available | 0 unavailable
StrategyType:           RollingUpdate
    Image:         nginx:1.27
kubectl apply -f <file> beginner Create or update resources from a manifest file, a folder or a URL.

Example

bash
kubectl apply -f k8s/
deployment.apps/web configured
service/web unchanged
ingress.networking.k8s.io/web created

Tip: apply is declarative: keep manifests in Git and apply them, instead of editing live objects.

kubectl diff -f <file> advanced Preview what apply would change on the cluster, as a unified diff.

Example

bash
kubectl diff -f deployment.yaml
-  replicas: 3
+  replicas: 5
-        image: nginx:1.27
+        image: nginx:1.27.2

Tip: Exit code 1 means there are differences. Great as a CI check before a deploy.

kubectl scale deployment <name> --replicas=<n> beginner Change the number of replicas immediately.

Example

bash
kubectl scale deployment web --replicas=5
deployment.apps/web scaled

Tip: If an HPA manages the Deployment, it overrides this. Change the HPA min/max instead.

kubectl set image deployment/<name> <container>=<image> intermediate Update a container image and trigger a rolling update.

Example

bash
kubectl set image deployment/web nginx=nginx:1.27.2
deployment.apps/web image updated
kubectl rollout status deployment/<name> intermediate Wait and report until a rollout finishes or fails.

Example

bash
kubectl rollout status deployment/web --timeout=120s
Waiting for deployment "web" rollout to finish: 2 of 3 updated replicas are available...
deployment "web" successfully rolled out

Tip: Use it in pipelines right after apply: it returns a non-zero exit code when the rollout fails or times out.

kubectl rollout history deployment/<name> intermediate List the revisions of a Deployment.

Example

bash
kubectl rollout history deployment/web
deployment.apps/web
REVISION  CHANGE-CAUSE
1         <none>
2         <none>
3         <none>

Tip: Add --revision=2 to see the full pod template of that revision.

kubectl rollout undo deployment/<name> intermediate Roll back to the previous revision, or to a specific one.

Example

bash
kubectl rollout undo deployment/web --to-revision=2
deployment.apps/web rolled back
kubectl rollout restart deployment/<name> beginner Recreate all pods with a rolling update, e.g. to load a changed ConfigMap.

Example

bash
kubectl rollout restart deployment/web
deployment.apps/web restarted
kubectl autoscale deployment <name> --min=<n> --max=<n> advanced Create a HorizontalPodAutoscaler that scales on CPU usage.

Example

bash
kubectl autoscale deployment web --min=2 --max=10 --cpu-percent=70
horizontalpodautoscaler.autoscaling/web autoscaled

Tip: The pods need CPU requests and metrics-server must be running, otherwise the HPA shows <unknown> targets.

Services & Networking

11 commands

Expose workloads, check endpoints, ingress and DNS.

kubectl get services beginner List Services with their type, cluster IP, external IP and ports.

Example

bash
kubectl get svc
NAME         TYPE           CLUSTER-IP      EXTERNAL-IP    PORT(S)        AGE
kubernetes   ClusterIP      10.96.0.1       <none>         443/TCP        42d
web          ClusterIP      10.96.120.45    <none>         80/TCP         3h
web-lb       LoadBalancer   10.96.201.18    203.0.113.25   80:31544/TCP   2h
kubectl expose deployment <name> --port=<port> beginner Create a Service that selects the Deployment's pods.

Example

bash
kubectl expose deployment web --port=80 --target-port=8080 --type=ClusterIP
service/web exposed

Tip: --port is what clients call; --target-port is what the container listens on.

kubectl describe service <name> beginner Show a Service's selector, ports and the pod IPs behind it.

Example

bash
kubectl describe svc web | grep -E 'Selector|Port|Endpoints'
Selector:          app=web
Port:              <unset>  80/TCP
TargetPort:        8080/TCP
Endpoints:         10.244.1.14:8080,10.244.2.9:8080

Tip: Empty Endpoints means the selector matches no ready pod: compare it with kubectl get pods --show-labels.

kubectl get endpointslices -l kubernetes.io/service-name=<svc> intermediate List the pod addresses a Service currently routes to.

Example

bash
kubectl get endpointslices -l kubernetes.io/service-name=web
NAME        ADDRESSTYPE   PORTS   ENDPOINTS                 AGE
web-8kq2d   IPv4          8080    10.244.1.14,10.244.2.9    3h

Tip: EndpointSlices replace the older Endpoints API, which is deprecated since Kubernetes 1.33.

kubectl port-forward svc/<name> <local>:<remote> beginner Reach a ClusterIP Service from your machine.

Example

bash
kubectl port-forward svc/web 8080:80
Forwarding from 127.0.0.1:8080 -> 8080
Forwarding from [::1]:8080 -> 8080

Tip: It connects to one pod behind the Service, so it is for debugging, not for load testing.

kubectl get ingress beginner List Ingress resources with their class, hosts and address.

Example

bash
kubectl get ingress -A
NAMESPACE   NAME   CLASS   HOSTS              ADDRESS        PORTS     AGE
default     web    nginx   blog.example.com   203.0.113.10   80, 443   2h
kubectl describe ingress <name> intermediate Show the routing rules, TLS secrets and backend Services of an Ingress.

Example

bash
kubectl describe ingress web | sed -n '/Rules:/,/Annotations:/p'
Rules:
  Host              Path  Backends
  ----              ----  --------
  blog.example.com
                    /   web:80 (10.244.1.14:8080,10.244.2.9:8080)
Annotations:        cert-manager.io/cluster-issuer: letsencrypt
kubectl get networkpolicies intermediate List NetworkPolicies and the pods they select.

Example

bash
kubectl get netpol -n prod
NAME               POD-SELECTOR   AGE
default-deny-all   <none>         10d
allow-web-to-db    app=postgres   10d

Tip: An empty POD-SELECTOR selects every pod in the namespace. Policies only work if your CNI enforces them.

kubectl run <name> --rm -it --image=busybox -- nslookup <host> intermediate Test cluster DNS from a throwaway pod that deletes itself on exit.

Example

bash
kubectl run dns-test --rm -it --restart=Never --image=busybox:1.36 -- nslookup web.default.svc.cluster.local
Server:    10.96.0.10
Address:   10.96.0.10:53

Name:      web.default.svc.cluster.local
Address:   10.96.120.45
pod "dns-test" deleted
kubectl run <name> --rm -it --image=curlimages/curl -- curl <url> intermediate Call a Service from inside the cluster network.

Example

bash
kubectl run curl-test --rm -it --restart=Never --image=curlimages/curl -- curl -sI http://web.default.svc.cluster.local
HTTP/1.1 200 OK
Server: nginx/1.27.2
Content-Type: text/html
pod "curl-test" deleted
kubectl get svc <name> -o jsonpath='{...}' advanced Extract one field, such as a load balancer's external IP, for scripts.

Example

bash
kubectl get svc web-lb -o jsonpath='{.status.loadBalancer.ingress[0].ip}'
203.0.113.25

Tip: Some clouds return a hostname instead of an IP: use .ingress[0].hostname there.

Namespaces

8 commands

Organize, isolate and set defaults per namespace.

kubectl get namespaces beginner List all namespaces and their status.

Example

bash
kubectl get ns
NAME              STATUS   AGE
default           Active   42d
kube-node-lease   Active   42d
kube-public       Active   42d
kube-system       Active   42d
prod              Active   20d
kubectl create namespace <name> beginner Create a namespace.

Example

bash
kubectl create namespace team-a
namespace/team-a created
kubectl config set-context --current --namespace=<name> beginner Make a namespace the default for the current context, so you can drop -n.

Example

bash
kubectl config set-context --current --namespace=team-a
Context "prod-cluster" modified.
kubectl get all -n <namespace> beginner List the common workload resources in a namespace.

Example

bash
kubectl get all -n team-a
NAME                       READY   STATUS    RESTARTS   AGE
pod/api-6b8f7d5c4d-qk9t2   1/1     Running   0          5m

NAME          TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)    AGE
service/api   ClusterIP   10.96.88.12    <none>        8080/TCP   5m

NAME                  READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/api   1/1     1            1           5m

Tip: "all" does not include ConfigMaps, Secrets, Ingresses or PVCs. List those explicitly.

kubectl label namespace <name> <key>=<value> intermediate Label a namespace, e.g. to enforce a Pod Security Standard.

Example

bash
kubectl label namespace team-a pod-security.kubernetes.io/enforce=restricted
namespace/team-a labeled
kubectl describe resourcequota -n <namespace> intermediate Show how much of the namespace quota is used.

Example

bash
kubectl describe resourcequota -n team-a
Name:            team-a-quota
Namespace:       team-a
Resource         Used  Hard
--------         ----  ----
limits.memory    2Gi   8Gi
pods             4     20
requests.cpu     500m  4

Tip: When a quota sets CPU or memory, every pod must declare requests/limits or it is rejected.

kubectl get limitrange -n <namespace> advanced List the default and maximum container resources in a namespace.

Example

bash
kubectl get limitrange -n team-a -o yaml | grep -A 4 'default:'
      default:
        cpu: 500m
        memory: 512Mi
      defaultRequest:
        cpu: 100m
kubectl delete namespace <name> intermediate Delete a namespace and everything inside it.

Example

bash
kubectl delete namespace team-a
namespace "team-a" deleted

Tip: There is no undo. A namespace stuck in Terminating usually has a finalizer waiting for a missing controller.

ConfigMaps & Secrets

9 commands

Manage configuration and credentials for your workloads.

kubectl create configmap <name> --from-literal=<key>=<value> beginner Create a ConfigMap from key/value pairs.

Example

bash
kubectl create configmap app-config --from-literal=LOG_LEVEL=info --from-literal=FEATURE_X=true
configmap/app-config created
kubectl create configmap <name> --from-file=<path> beginner Create a ConfigMap from a file; the file name becomes the key.

Example

bash
kubectl create configmap nginx-conf --from-file=nginx.conf
configmap/nginx-conf created
kubectl get configmap <name> -o yaml beginner Show the data stored in a ConfigMap.

Example

bash
kubectl get configmap app-config -o yaml | grep -A 2 '^data:'
data:
  FEATURE_X: "true"
  LOG_LEVEL: info
kubectl create configmap <name> --dry-run=client -o yaml intermediate Generate a manifest instead of creating the object, ready to commit to Git.

Example

bash
kubectl create configmap app-config --from-env-file=.env --dry-run=client -o yaml > configmap.yaml

Tip: Works with every kubectl create subcommand: the fastest way to scaffold correct YAML.

kubectl create secret generic <name> --from-literal=<key>=<value> beginner Create an Opaque Secret from key/value pairs.

Example

bash
kubectl create secret generic db-creds --from-literal=username=app --from-file=password=./db-password.txt
secret/db-creds created

Tip: Literal values end up in your shell history. Prefer --from-file for real passwords.

kubectl create secret docker-registry <name> intermediate Store private registry credentials for imagePullSecrets.

Example

bash
kubectl create secret docker-registry ghcr-cred \
  --docker-server=ghcr.io \
  --docker-username=jeff \
  --docker-password="$GHCR_TOKEN"
secret/ghcr-cred created
kubectl create secret tls <name> --cert=<file> --key=<file> intermediate Store a TLS certificate and key, e.g. for an Ingress.

Example

bash
kubectl create secret tls blog-tls --cert=tls.crt --key=tls.key
secret/blog-tls created
kubectl get secret <name> -o jsonpath='{.data.<key>}' | base64 -d intermediate Decode a single value from a Secret.

Example

bash
kubectl get secret db-creds -o jsonpath='{.data.username}' | base64 -d
app

Tip: Secrets are base64-encoded, not encrypted. Restrict who can get them with RBAC and enable encryption at rest.

kubectl edit configmap <name> intermediate Edit a live ConfigMap in your $EDITOR.

Example

bash
KUBE_EDITOR="code --wait" kubectl edit configmap app-config
configmap/app-config edited

Tip: Env vars from a ConfigMap only change after a restart: run kubectl rollout restart afterwards.

Storage

8 commands

Work with storage classes, volumes and claims.

kubectl get storageclass beginner List storage classes; the default one is marked.

Example

bash
kubectl get sc
NAME                 PROVISIONER          RECLAIMPOLICY   VOLUMEBINDINGMODE      ALLOWVOLUMEEXPANSION   AGE
oci-bv (default)     blockvolume.csi...   Delete          WaitForFirstConsumer   true                   42d
local-path           rancher.io/...       Delete          WaitForFirstConsumer   false                  42d
kubectl get pv beginner List PersistentVolumes (cluster-wide) and the claims bound to them.

Example

bash
kubectl get pv
NAME                                       CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM            STORAGECLASS
pvc-3f1c2a7e-5b9d-4e8a-9c41-0d2e7f6a1b38   20Gi       RWO            Delete           Bound    prod/data-pg-0   oci-bv
kubectl get pvc -n <namespace> beginner List PersistentVolumeClaims and whether they are bound.

Example

bash
kubectl get pvc -n prod
NAME        STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   AGE
data-pg-0   Bound    pvc-3f1c2a7e-5b9d-4e8a-9c41-0d2e7f6a1b38   20Gi       RWO            oci-bv         20d
kubectl describe pvc <name> intermediate Explain why a claim is Pending and which pod uses it.

Example

bash
kubectl describe pvc uploads -n prod | tail -3
  Type    Reason                Age   From                         Message
  ----    ------                ----  ----                         -------
  Normal  WaitForFirstConsumer  12s   persistentvolume-controller  waiting for first consumer to be created before binding

Tip: WaitForFirstConsumer is normal: the volume is created only once a pod using the claim is scheduled.

kubectl apply -f - <<EOF intermediate Create a claim inline with a heredoc, without a separate file.

Example

bash
kubectl apply -f - <<EOF
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: uploads
spec:
  accessModes: [ReadWriteOnce]
  resources:
    requests:
      storage: 10Gi
EOF
persistentvolumeclaim/uploads created
kubectl patch pvc <name> -p '<json>' advanced Grow a volume by raising the claim's requested size.

Example

bash
kubectl patch pvc data-pg-0 -n prod -p '{"spec":{"resources":{"requests":{"storage":"40Gi"}}}}'
persistentvolumeclaim/data-pg-0 patched

Tip: Only works when the storage class has allowVolumeExpansion: true. Volumes can grow, never shrink.

kubectl get volumeattachments advanced See which CSI volumes are attached to which nodes.

Example

bash
kubectl get volumeattachments
NAME                                                                   ATTACHER             PV                                         NODE       ATTACHED   AGE
csi-5c0e9a1d7f3b4e62a8d91c7b2f0e4a6d5b8c3e1f9a2d7b4c6e0f8a1d3b5c7e9f   blockvolume.csi...   pvc-3f1c2a7e-5b9d-4e8a-9c41-0d2e7f6a1b38   worker-1   true       20d

Tip: A pod stuck in ContainerCreating with a Multi-Attach error usually means the old attachment was not released yet.

kubectl delete pvc <name> intermediate Delete a claim. With reclaim policy Delete, the data is gone too.

Example

bash
kubectl delete pvc uploads
persistentvolumeclaim "uploads" deleted

Tip: For important data, set the PV reclaim policy to Retain before deleting the claim.

Troubleshooting

12 commands

Find out why something is failing: events, debug containers, permissions.

kubectl get events --sort-by=.lastTimestamp beginner Show the namespace events in time order, newest last.

Example

bash
kubectl get events -n prod --sort-by=.lastTimestamp | tail -3
LAST SEEN   TYPE      REASON      OBJECT                    MESSAGE
2m          Warning   BackOff     pod/worker-5f6c7d9b-9pl2d Back-off restarting failed container worker
30s         Normal    Pulled      pod/web-7d4b9c8f6-zt8wm   Container image "nginx:1.27.2" already present on machine
kubectl get events --field-selector type=Warning intermediate Show only warnings, across all namespaces with -A.

Example

bash
kubectl get events -A --field-selector type=Warning
NAMESPACE   LAST SEEN   TYPE      REASON             OBJECT                       MESSAGE
prod        4m          Warning   FailedScheduling   pod/api-6b8f7d5c4d-r7xw2     0/3 nodes are available: 3 Insufficient memory.
kubectl get pods -A --field-selector=status.phase!=Running intermediate Find every pod that is not running: Pending, Failed, Succeeded or Unknown.

Example

bash
kubectl get pods -A --field-selector=status.phase!=Running
NAMESPACE   NAME                     READY   STATUS      RESTARTS   AGE
prod        api-6b8f7d5c4d-r7xw2     0/1     Pending     0          4m
batch       report-28812345-6kx9p    0/1     Completed   0          1h

Tip: CrashLoopBackOff pods are still in the Running phase, so check the RESTARTS column too.

kubectl top pods intermediate Show live CPU and memory per pod, sorted to find the heaviest.

Example

bash
kubectl top pods -n prod --sort-by=memory --containers
POD                    NAME     CPU(cores)   MEMORY(bytes)
pg-0                   postgres 85m          1210Mi
api-6b8f7d5c4d-qk9t2   api      120m         310Mi
kubectl logs -l <selector> --all-containers --prefix intermediate Read logs from every pod of an app at once, prefixed with pod and container.

Example

bash
kubectl logs -l app=web --all-containers --prefix --tail=2
[pod/web-7d4b9c8f6-x2kqp/nginx] 10.244.2.5 - - "GET / HTTP/1.1" 200 615
[pod/web-7d4b9c8f6-zt8wm/nginx] 10.244.1.3 - - "GET /healthz HTTP/1.1" 200 2
kubectl debug -it <pod> --image=<image> --target=<container> advanced Attach an ephemeral debug container to a running pod, sharing its processes.

Example

bash
kubectl debug -it web-7d4b9c8f6-x2kqp --image=busybox:1.36 --target=nginx
Targeting container "nginx". If you don't see processes from this container it may be because the container runtime doesn't support this feature.
Defaulting debug container name to debugger-8xk2p.
If you don't see a command prompt, try pressing enter.
/ #

Tip: The way to debug distroless or scratch images that have no shell.

kubectl debug node/<name> -it --image=<image> advanced Get a shell on a node through a privileged pod; the host filesystem is at /host.

Example

bash
kubectl debug node/worker-1 -it --image=ubuntu:24.04
Creating debugging pod node-debugger-worker-1-q8w2n with container debugger on node worker-1.
If you don't see a command prompt, try pressing enter.
root@worker-1:/#

Tip: Delete the node-debugger pod when you are done; it is not removed automatically.

kubectl auth can-i <verb> <resource> intermediate Check whether you, or another identity with --as, may perform an action.

Example

bash
kubectl auth can-i create deployments -n prod --as=system:serviceaccount:ci:deployer
yes
kubectl auth can-i --list advanced List everything the current identity is allowed to do in a namespace.

Example

bash
kubectl auth can-i --list -n prod | head -4
Resources                          Non-Resource URLs   Resource Names   Verbs
pods                               []                  []               [get list watch]
deployments.apps                   []                  []               [get list watch create update patch]
selfsubjectreviews.authentication.k8s.io   []          []               [create]
kubectl wait --for=condition=<condition> <resource> intermediate Block until resources reach a condition. Ideal in scripts and CI.

Example

bash
kubectl wait --for=condition=Ready pod -l app=web --timeout=120s
pod/web-7d4b9c8f6-x2kqp condition met
pod/web-7d4b9c8f6-zt8wm condition met
kubectl explain <resource.field> beginner Read the built-in API docs for any field, straight from the cluster.

Example

bash
kubectl explain deployment.spec.strategy.rollingUpdate.maxSurge | head -6
GROUP:      apps
KIND:       Deployment
VERSION:    v1

FIELD: maxSurge <IntOrString>

Tip: Add --recursive to print the whole field tree of a resource.

kubectl cluster-info dump --output-directory=<dir> advanced Save cluster state, events and pod logs to files for offline analysis.

Example

bash
kubectl cluster-info dump --namespaces prod --output-directory=./cluster-dump
Cluster info dumped to ./cluster-dump

Tip: Check the dump before sharing it: it can contain environment variables and other sensitive data.

↑ ↓ navigate Enter open Esc close