CertGrid CertGrid

kubectl cheat sheet

The kubectl you actually type, grouped by what you are trying to find out. Every command here appears in a guide in this path that was captured against a real cluster.

Context and connection

  • kubectl config get-contexts

    List every context in the kubeconfig and mark the current one.

    The first command to run when output surprises you: the wrong context explains symptoms that make no sense in the cluster you thought you were in.

    Full guide
  • kubectl config use-context <name>

    Switch the active context.

    Full guide
  • kubectl config view --minify -o jsonpath='{.clusters[0].cluster.server}'

    Print the API server address the current context talks to.

    Full guide
  • kubectl config set-context --current --namespace=<ns>

    Change the default namespace for the current context, so -n can be omitted.

    Full guide
  • kubectl cluster-info

    Show the control plane endpoint and the CoreDNS proxy URL.

    Full guide
  • kubectl version --client=true -o json

    Client version, including the embedded kustomize version.

    The kustomize number matters: a kustomization that works with the standalone binary and not with kubectl is nearly always a version difference.

    Full guide
  • kubectl auth can-i <verb> <resource> -n <ns>

    Ask the API server whether you are permitted an action, without attempting it.

    Full guide
  • kubectl auth can-i --list -n <ns>

    Everything you are allowed in a namespace, which is faster than reading bindings.

    Full guide

Finding out what exists

  • kubectl api-resources

    Every resource type this cluster serves, with short names and whether it is namespaced.

    The honest answer to "what can this cluster do". CRDs appear here alongside built-in types.

    Full guide
  • kubectl api-resources --api-group=<group>

    Just one API group's resources, which is how you check a CRD registered.

    Full guide
  • kubectl explain <resource>.<field>

    Field documentation generated from the schema, including required fields and enums.

    Works on CRDs too, and is the fastest way to check a field name before writing YAML.

    Full guide
  • kubectl get <resource> -A

    Across every namespace, not just the current one.

    Full guide
  • kubectl get all -n <ns>

    The common workload and Service types in a namespace.

    Misleading name: it does not include ConfigMaps, Secrets, PVCs, Ingresses or CRs. It is a shortcut, not an audit.

    Full guide
  • kubectl get --raw='/version'

    Make a raw HTTP request to the API and print the response.

    kubectl is an HTTP client. Useful for endpoints with no kubectl verb, like /livez and /metrics.

    Full guide

Reading objects precisely

  • kubectl get pods -o wide

    Adds node, Pod IP and nominated node to the default columns.

    Full guide
  • kubectl get pod <name> -o yaml

    The whole object as the API server stores it, spec and status.

    Full guide
  • kubectl get pod <name> -o jsonpath='{.status.containerStatuses[0].state}'

    One field, script-friendly. `state` is waiting, running or terminated.

    Full guide
  • kubectl get pods -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName

    Pick your own columns from any fields.

    Better than jsonpath for lists, because it prints a header and aligns.

    Full guide
  • kubectl get pods --show-labels

    Every label on every Pod, which is what selectors actually match.

    The first check when a Service has no endpoints or a NetworkPolicy is not matching.

    Full guide
  • kubectl get pods -l app=web,tier!=cache

    Filter by label, including inequality.

    Full guide
  • kubectl get pods --field-selector=status.phase!=Running,status.phase!=Succeeded

    Every Pod that is neither running nor finished. Scales to thousands of Pods.

    Field selectors are evaluated by the API server, unlike a client-side grep.

    Full guide
  • kubectl get pods --sort-by=.status.containerStatuses[0].restartCount

    Order by any field. Restart count finds the unstable Pods.

    Full guide
  • kubectl describe <resource> <name>

    A readable summary plus the object's events at the bottom.

    The From column in the events block names the component: default-scheduler is placement, kubelet is everything after it.

    Full guide

Creating and changing

  • kubectl apply -f <file-or-dir>

    Send desired state. Idempotent: the same file twice reports `unchanged`.

    Full guide
  • kubectl diff -f <file>

    What would change if you applied it. Exit 0 means the cluster already matches.

    Usable as a CI drift check. No output and exit 0 is the pass condition.

    Full guide
  • kubectl apply --server-side -f <file>

    Apply with server-side field ownership instead of a last-applied annotation.

    Required for very large CRDs: client-side apply stores the manifest in an annotation and annotations are capped at 256KB.

    Full guide
  • kubectl create <resource> <name> --dry-run=client -o yaml

    Generate a manifest skeleton without creating anything.

    The fastest way to start a manifest, and the standard exam technique.

    Full guide
  • kubectl patch <resource> <name> --type=merge -p '{"spec":{"replicas":3}}'

    Change specific fields without sending the whole object.

    Full guide
  • kubectl patch <resource> <name> --subresource=status --type=merge -p '{...}'

    Write the status subresource, which the main endpoint ignores.

    A plain patch writing status reports `patched (no change)`. That is the subresource split, not a failure.

    Full guide
  • kubectl label <resource> <name> <key>=<value> --overwrite

    Add or change a label. Without --overwrite an existing key is refused.

    Full guide
  • kubectl scale deploy/<name> --replicas=<n>

    Change the replica count imperatively.

    Leaves the cluster out of step with your manifests, and Helm or the next apply will revert it.

    Full guide
  • kubectl delete <resource> <name> Destructive

    Delete an object. Children with owner references go with it.

    Full guide
  • kubectl delete crd <name> Whole-host

    Delete a CustomResourceDefinition, and with it every custom resource of that kind in every namespace.

    No confirmation and no undo. Run `kubectl get <plural> -A` first, every time.

    Full guide

Workloads and rollouts

  • kubectl rollout status deploy/<name> --timeout=180s

    Wait for a rollout, with a non-zero exit if it does not finish in time.

    Full guide
  • kubectl rollout history deploy/<name>

    The revisions a Deployment can be rolled back to.

    Full guide
  • kubectl rollout undo deploy/<name>

    Roll back to the previous revision.

    On an object managed by `kubectl apply`, this warns that the last-applied record is now out of step. The warning is real.

    Full guide
  • kubectl rollout restart deploy/<name>

    Force a rolling restart by stamping the Pod template.

    The correct way to make Pods pick up a changed ConfigMap that has a fixed name.

    Full guide
  • kubectl set image deploy/<name> <container>=<image>

    Change one container's image, triggering a rollout.

    Full guide
  • kubectl wait --for=condition=Available deploy/<name> --timeout=60s

    Block until a condition is met. Non-zero exit on timeout.

    Full guide
  • kubectl wait --for=jsonpath='{.status.phase}'=Succeeded pod/<name>

    Wait on an arbitrary field when no condition expresses what you need.

    Full guide
  • kubectl get rs

    ReplicaSets, which is where a stuck rollout is visible: a new one at 0 ready beside an old one still serving.

    Full guide
  • kubectl create job <name> --from=cronjob/<name>

    Run a CronJob immediately without waiting for its schedule.

    Full guide

Getting inside a container

  • kubectl logs <pod>

    The current container's stdout and stderr.

    Full guide
  • kubectl logs <pod> -c <container>

    One container in a multi-container Pod. Required when there is more than one.

    Full guide
  • kubectl logs <pod> --previous

    The previous run's logs, which is where a crash loop's cause is.

    The single most useful flag on this command. The current run may show nothing at all.

    Full guide
  • kubectl logs -f <pod> --tail=50

    Follow, starting from the last 50 lines.

    Full guide
  • kubectl logs -l app=web --all-containers=true

    Logs from every Pod matching a label selector.

    Full guide
  • kubectl logs deploy/<name>

    Logs from one Pod of a Deployment, chosen for you.

    One Pod, not all of them. With several replicas you may be reading the wrong one.

    Full guide
  • kubectl exec -it <pod> -- sh

    A shell in a running container.

    Full guide
  • kubectl debug -it <pod> --image=busybox:1.36 --target=<container>

    Attach an ephemeral debug container sharing the target's process namespace.

    The answer for a distroless or scratch image with no shell of its own.

    Full guide
  • kubectl debug node/<node> -it --image=busybox:1.36

    A Pod on a node's host namespaces, for inspecting the node itself.

    Full guide
  • kubectl cp <pod>:<path> <local-path>

    Copy a file out of a container. Needs tar in the image.

    Full guide
  • kubectl port-forward svc/<name> 8080:80

    Tunnel a local port to a Service or Pod through the API server.

    Bypasses Ingress and NetworkPolicy entirely, so it proves the backend works and nothing about the path to it.

    Full guide
  • kubectl run probe --rm -it --restart=Never --image=busybox:1.36 -- sh

    A throwaway Pod for testing connectivity from inside the cluster.

    In a script piped to a shell, -i consumes the rest of the script. Use --command with kubectl logs instead.

    Full guide

Nodes and capacity

  • kubectl get nodes -o wide

    Node status, roles, version, addresses and OS image.

    Check the version column: a node left behind by a partial upgrade explains behaviour that differs by node.

    Full guide
  • kubectl describe node <name>

    Conditions, allocated resources, taints and the Pods running there.

    For the four pressure and network conditions, False is healthy. Only Ready inverts.

    Full guide
  • kubectl top nodes

    Actual CPU and memory usage, from metrics-server.

    Usage, not requests. The scheduler places by requests, so a node can be idle and fully booked.

    Full guide
  • kubectl top pods --containers

    Per-container usage, which is what you compare against limits.

    Full guide
  • kubectl cordon <node>

    Mark unschedulable. Existing Pods stay.

    Full guide
  • kubectl drain <node> --ignore-daemonsets --delete-emptydir-data Caution

    Cordon and evict, respecting PodDisruptionBudgets.

    Evicts Pods. --delete-emptydir-data destroys emptyDir contents, so know what is in them first.

    Full guide
  • kubectl uncordon <node>

    Make the node schedulable again. Easy to forget after an upgrade.

    Full guide
  • kubectl taint node <name> key=value:NoSchedule

    Add a taint. A trailing minus removes it.

    Full guide

Events and triage

  • kubectl get events -A --field-selector type=Warning --sort-by=.lastTimestamp

    Every warning in the cluster, newest last. The single highest-value triage command.

    Events expire after an hour by default, so no warnings is not proof of health.

    Full guide
  • kubectl get events -n <ns> --sort-by=.lastTimestamp

    One namespace in chronological order. Default ordering is not chronological.

    Full guide
  • kubectl get --raw='/livez?verbose'

    API server health broken down by subsystem. A failing check is marked with a minus.

    Full guide
  • kubectl get --raw='/readyz'

    Whether the API server is ready to serve, as distinct from alive.

    Full guide
  • kubectl -n kube-system get lease kube-scheduler -o jsonpath='{.spec.holderIdentity}'

    Which node currently holds the scheduler leadership lease.

    Full guide
  • kubectl get pods -n kube-system

    The control plane and add-ons. Restart counts climbing means something is crash-looping.

    Full guide