kubectl Cheatsheet - Pods, Deploy, Logs & Apply Commands

A kubectl command reference for app developers and cluster operators, covering resource queries, Pod diagnosis, replica scaling, and cluster context management. Unlike reading YAML directly, kubectl is the consistent window into cluster state and change control, letting you quickly localize frequent incidents such as CrashLoopBackOff, Pods stuck in Pending, and failed rollouts. By the end you can run the whole loop yourself: inspect status → check events → read logs → recover or roll back.

Containers & Orchestration·46 commands·Last updated 2026-09-10
kubectlkubernetespodTroubleshooting

Typical Use Case

For Kubernetes ops and delivery: inspect resource status, scale and roll out updates, and troubleshoot Pods stuck in Pending / CrashLoopBackOff / ImagePullBackOff, plus reading logs and events to find root causes.

Get Resources 5

kubectl get pods -n prod
List pods in a namespace
kubectl get pods -o wide
Show extra info: node and pod IP
kubectl get pods -A
List pods across all namespaces
kubectl get svc,ingress -n prod
Query Services and Ingresses at once
kubectl get events --sort-by=.lastTimestamp
Sort events by time, find scheduling/pull failures

Describe & Diagnose 5

kubectl describe pod <pod> -n prod
Check events, container status, probes for CrashLoop/Pending
kubectl logs <pod> -n prod
View pod logs
kubectl logs <pod> --previous
View logs from the previous crashed container, essential for CrashLoop
kubectl logs <pod> -c <container>
Logs for a specific container in a multi-container pod
kubectl exec -it <pod> -- sh
Shell into a pod container for debugging

Scale & Rollout 5

kubectl scale deploy/app --replicas=3
Adjust replica count
kubectl rollout status deploy/app
Check rolling update progress
kubectl rollout undo deploy/app
Rollback to previous version
kubectl set image deploy/app c=app:1.1
Update image to trigger rolling update
kubectl delete pod <pod>
Delete pod, controller recreates automatically

Context & Configuration 4

kubectl config get-contexts
List all cluster contexts
kubectl config use-context <ctx>
Switch current cluster context, essential for multi-cluster
kubectl config set-context --current --namespace=prod
Set default namespace, saves typing -n each time
kubectl top pod -n prod
View pod CPU/memory usage, requires metrics-server

FAQ 5

Q: How do I list pods across all namespaces?
A: kubectl get pods -A or kubectl get pods --all-namespaces lists pods in every namespace of the cluster.
Q: What is the difference between kubectl apply and kubectl create?
A: kubectl apply is declarative (recommended) and supports create and update; kubectl create is imperative and errors if the resource already exists.
Q: How do I view a pod log?
A: kubectl logs <pod> -n <namespace>; add -f to follow, or --previous to see the crashed container logs.
Q: How do I shell into a pod container?
A: kubectl exec -it <pod> -- sh (or /bin/bash); use -c <container> for multi-container pods.
Q: How do I check cluster node status?
A: kubectl get nodes lists all node statuses; kubectl describe node <name> shows detailed node info.

Debugging & Output Formatting (REQ-02 add-on) 22

kubectl get pods --field-selector=status.phase=Running
List only pods in Running phase
kubectl get nodes --selector='!node-role.kubernetes.io/control-plane'
List worker nodes only, excluding control plane
kubectl get pods --show-labels
Show all labels attached to pods
kubectl get services --sort-by=.metadata.name
List services sorted by name
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'
Sort pods by restart count to spot crashes
kubectl get pv --sort-by=.spec.capacity.storage
Sort persistent volumes by capacity
kubectl get nodes -o jsonpath={.items[*].status.addresses[?(@.type=="ExternalIP")].address}
Extract external IPs of all nodes
kubectl get secret my-secret -o go-template={{range $k,$v := .data}}{{$k}}:{{$v|base64decode}}{{end}}
Decode and print all secret key-values at once
kubectl get pods -A -o=custom-columns='DATA:spec.containers[*].image'
List every container image running in the cluster
kubectl get node -o custom-columns='NODE_NAME:.metadata.name,STATUS:.status.conditions[?(@.type=="Ready")].status'
Show node readiness via custom columns
kubectl diff -f ./my-manifest.yaml
Diff live state against the applied manifest
kubectl patch node k8s-node-1 -p {"spec":{"unschedulable":true}}
Partially update a node to unschedulable
kubectl patch deployment web --subresource=scale --type=merge -p {"spec":{"replicas":2}}
Change replicas through the scale subresource
kubectl replace --force -f ./pod.json
Force replace a resource (delete then create)
kubectl expose deployment web --port=80 --target-port=8000
Expose a workload as a Service
kubectl logs -f -l name=myLabel --all-containers
Stream logs of all containers by label
kubectl logs my-pod --previous
Show logs of the previous crashed instance
kubectl debug my-pod -it --image=busybox:1.28
Create an interactive debug container in a pod
kubectl debug node/my-node -it --image=busybox:1.28
Create a debugging session on a node
kubectl cluster-info dump --output-directory=/path/to/cluster-state
Dump cluster state snapshot to a directory
kubectl api-resources --verbs=list,get
List resource types supporting given verbs
kubectl run nginx --image=nginx --dry-run=client -o yaml > pod.yaml
Generate a pod manifest without creating it

Parameter matrix

参数EffectExample
-n指定命名空间,避免操作默认空间kubectl -n prod get pods
-o输出格式(yaml/json/wide/name)kubectl get pod web -o yaml
--kubeconfig指定集群凭证文件kubectl --kubeconfig ~/.kube/prod get nodes
-f按 YAML 文件创建/应用/删除资源kubectl apply -f deploy.yaml
--dry-run=client仅校验不创建,可生成清单kubectl run nginx --image=nginx --dry-run=client -o yaml
-l按标签筛选资源kubectl get pods -l app=web
--previous查看上一次崩溃容器的日志kubectl logs web --previous
-c指定多容器 Pod 中的某个容器kubectl logs web -c app
--watch持续观察资源变化kubectl get pods --watch
--record记录变更原因到修订历史kubectl set image deploy/web app=new:1.1 --record

Common pitfalls

SymptomPod 长时间处于 Pending。

Cause节点资源不足、没有匹配的节点(taint/亲和),或 PVC 无法绑定。

Fixkubectl describe pod 看 Events;检查节点资源(kubectl top nodes)与 PVC 状态;放宽资源请求或污点容忍。

SymptomPod 反复重启,状态 CrashLoopBackOff。

Cause应用启动即崩溃(配置错误、依赖未就绪、端口被占),或探针失败。

Fixkubectl logs web --previous 看上一次崩溃日志;kubectl describe pod 看 Last State 与 Events;修正启动命令或探针阈值。

Symptom镜像拉取失败,状态 ImagePullBackOff / ErrImagePull。

Cause镜像名/标签写错、私有仓库未配置 imagePullSecret、或节点无法访问仓库。

Fix核对镜像地址与 tag;为私有仓库配置 imagePullSecrets;在节点上手动 crictl pull 验证网络。

Symptomkubectl top 报错 metrics not available。

Cause集群未安装 metrics-server,不是命令写错。

Fix确认 metrics-server 已部署(kubectl get apiservice v1beta1.metrics.k8s.io);安装后再用 top。

Symptom误在本地把资源改到了生产集群。

Cause当前 context 指向生产,操作时未确认集群。

Fix任何写操作前执行 kubectl config get-contexts 与 kubectl config current-context 确认;用别名或工具防止误操作。

Symptomapply 之后改动未生效。

Cause字段被其他控制器(如 HPA、Operator)覆盖,或字段不可变。

Fixkubectl get 看实际值;对不可变字段(如 selector)需删除重建;排查是否有 controller 在管理该资源。

Troubleshooting

  1. 1先看 Pod 状态与事件

    kubectl describe pod web

    Events 段通常有最直接的失败原因(FailedScheduling、BackOff、FailedMount 等)。

  2. 2读应用日志(含上一次崩溃)

    kubectl logs web --previous -c app

    CrashLoop 时当前容器已退出,必须加 --previous 才能看到崩溃前的输出。

  3. 3确认节点资源与调度

    kubectl top nodes

    Pending 多半是 CPU/内存不足或没有可调度节点。

  4. 4查看完整修订历史以便回滚

    kubectl rollout history deploy/web

    确认有可回滚版本后再 kubectl rollout undo deploy/web 回退。

Tips

  • Troubleshooting order: get for status → describe for events → logs for app errors, add --previous for CrashLoop.
  • Run kubectl config get-contexts first to confirm the current cluster to avoid accidental operations on production.
  • kubectl top errors usually mean metrics-server is not installed, not a command syntax issue.

Official References

Each command links to its official documentation below, so you can verify the latest usage and read deeper.

Maintained by LaoHand

Publicly updated on Sep 10, 2026, continuously proofread against official docs.

Contact Us

Wrong command or description? Send us corrections, business inquiries or product feedback by email.

Contact Us