Kubernetes Commands Cheat Sheet

Common Kubernetes commands: kubectl get, apply, delete, scale, rollout, port-forward and more, with notes for everyday cluster ops and troubleshooting.

How It Works

Kubernetes orchestrates containerized apps: containers live in Pods (the smallest scheduling unit), Deployments manage replicas and rolling updates, and Services give a stable entry point. The core idea is "declare the desired state; the system continuously reconciles toward it".

kubectl supports both imperative (run/create changes the cluster directly) and declarative (apply -f with YAML describing desired state, reconciled by controllers) styles. Debug with logs/describe/exec, scale with scale, ship with rollout.

When to Use This Table

This table is for troubleshooting a live cluster. Kubernetes debugging is highly pattern-based: a Pod that will not start needs describe and logs, uneven replicas mean looking at pod distribution and node affinity, a stuck release means rollout status, and capacity problems surface in describe node. The commands are fixed; the judgement order is what matters.

When not to consult it: you are making architecture or technology choices. kubectl addresses how to observe and modify, never which structure to use — Deployment versus StatefulSet is a design decision, not a command.

Rule of thumb: a command that changes state is a write (apply/edit/delete/scale), and the read-only set is only get, describe, logs and explain. During debugging stay read-only until the picture is clear, because a single careless command destroys the evidence you need.

Mind that kubectl is not SSH: it talks to the API Server, every action is authorised by RBAC and written to the audit log. There is no undo for kubectl delete in production, so archive with kubectl get -o yaml > backup.yaml before any destructive command.

Boundaries and Common Pitfalls

  • Pending almost always means image pull

    When a Pod stays Pending and no replicas are Running, it is almost always a failing image pull. Read the Events section of describe pod and look for three causes: a missing repository or mistyped tag, absent imagePullSecrets for a private registry, or network isolation preventing the node from reaching the registry. The Events block is the first place to look, faster than guessing.

  • The cause of CrashLoopBackOff is in the previous run log

    Reading current logs is often empty or misleading because the container has already died. Use kubectl logs <pod> --previous to get the last instance output, which holds the actual crash. Also note that the backoff restart policy widens the interval across failures (up to five minutes), so "it will settle on its own" is usually just backoff engaging, not the problem healing.

  • Omitted and explicit values behave differently during rolling updates

    Changing a Deployment template without touching its selector fails outright, while changing the selector spawns a new ReplicaSet and keeps the old one, which looks like an extra set of replicas rather than an in-place update. The same applies with HPA: it finds its target through the selector, so changing it silently breaks autoscaling.

  • The gap between requests and limits governs scheduling and throttling

    Without requests, the scheduler scores nodes on allocatable capacity and may place a Pod on a marginal node that evicts it at peak. With requests but too-tight limits, the container gets OOMKilled under memory pressure and a restart storm hides the real error. A workable default is requests at the measured P95, limits with generous headroom, and both within the same resource class so scheduling and throttling do not fight each other.

How This Relates to Neighbours

This table is a quick set of common commands, not a manual; kubectl <cmd> --help and the official docs are authoritative for the full flag surface.

For authoring or validating K8s YAML, this table has no schema reference; JSON Schema validation beats manual comparison.

When the problem is connectivity, DNS, Ingress or certificates, the cause usually lives outside the cluster (DNS provider, load balancer, CA) — kubectl can observe but not fix it.

If you only need to format or diff YAML, use the in-site YAML tools; this table only covers cluster interaction.

Practical Snippet

Key points: (1) stay read-only (get/describe/logs/explain) while debugging — writes destroy the evidence; (2) the Events block is the first place for image-pull and scheduling failures, more direct than re-reading Pod status; (3) get crash reasons from --previous, never the current log; (4) archive with -o yaml before any delete/scale/apply, since API Server writes are audited but have no undo.

# 只读排障顺序:先看清现状,再动手改
# ① 集群活着吗
kubectl cluster-info
kubectl get nodes -o wide

# ② Pod 到底卡在哪:Pending / CrashLoop / Running 但不 Ready
kubectl get pods -A -o wide | grep -vE "Running|Completed"
# 排障期间只看这一列:READY 永远是 1/N 就说明没就绪
        kubectl get pods -A | awk 'NR>1 && $2!~/^([0-9]+)/\1$/'

# ③ 事件是排障第一现场(镜像拉取、调度失败、资源不足都在这里)
kubectl describe pod -n <ns> <pod> | sed -n '/Events:/,$p'

# ④ 崩溃原因在上一轮日志,不是当前日志
kubectl logs <pod> --previous --tail=200

# ⑤ 状态分布与节点亲和
kubectl get pods -n <ns> -o custom-columns='NAME:.metadata.name,NODE:.spec.nodeName,STATUS:.status.phase'

# 改之前先存档(kubectl delete 没有回滚)
kubectl get deploy <name> -n <ns> -o yaml > backup.yaml

Practical Notes

  • kubectl apply and create differ once the resource existscreate errors out on an existing resource while apply performs a three-way merge. When other controllers write the same fields, apply reports a conflict — inspect whether last-applied-configuration has drifted from the live object.
  • Deleting a pod rebuilds it; it does not fix anythingPods are owned by a Deployment or StatefulSet, so the controller immediately starts a replacement and the failure can repeat identically. Diagnose with kubectl describe Events and the previous container logs (--previous).
  • Missing resource limits cause node-level avalanchesA Pod without requests/limits can consume all node memory and trigger the OOM killer against its neighbours. Set requests at minimum and memory limits in production, otherwise the scheduler cannot place workloads sensibly.

Data Sources

  • Kubernetes documentation (kubernetes.io/docs)
  • kubectl reference

Codes, names and definitions above come from public specifications; we claim no originality over the specification data itself. The arrangement, Chinese annotations and practical notes on this page are written by us.

CommandDescription
kubectl versionShow client and server version
kubectl cluster-infoShow cluster control-plane address
kubectl get nodesList cluster nodes (-o wide)
kubectl get podsList pods (-A all namespaces)
kubectl get servicesList services
kubectl get deploymentsList deployments
kubectl describe podShow pod details and events
kubectl logsShow pod logs (-f follow)
kubectl execRun a command in a container (-it)
kubectl apply -fCreate/update from a manifest
kubectl createCreate a resource imperatively
kubectl deleteDelete a resource (-f or name)
kubectl editEdit a resource live
kubectl scaleScale replica count
kubectl rollout statusShow rollout progress
kubectl rollout undoUndo a rollout
kubectl port-forwardForward a local port to a pod
kubectl exposeExpose a resource as a service
kubectl config get-contextsList kubeconfig contexts
kubectl config use-contextSwitch current context
kubectl top nodesShow node CPU/memory usage
kubectl top podsShow pod resource usage
kubectl cpCopy files between container and local
kubectl cordonMark a node unschedulable
kubectl uncordonMark a node schedulable
kubectl drainDrain a node for maintenance
kubectl get allList all resources in a namespace

Frequently Asked Questions

What is the difference between kubectl apply and create?

apply is declarative: it diffs the manifest against cluster state and makes incremental changes, safe to re-run and ideal for GitOps; create is imperative and errors on re-run.

How do I find why a pod keeps crashing?

First kubectl describe pod <name> to inspect Events and Last State (Exit Code, Reason); then kubectl logs --previous to see logs from the crashed container.

How do I port-forward to a pod for local debugging?

Use kubectl port-forward pod/<name> 8080:80 to map local 8080 to the pod's 80, then hit localhost:8080—no Service exposure needed.

How do I roll back a failed rollout?

kubectl rollout undo deployment/<name> reverts to the previous revision; kubectl rollout history deployment/<name> lists revisions, and --to-revision=N targets a specific one.