TL;DR
kubectl get pods to check status, kubectl logs -f <pod> to follow logs, kubectl exec -it <pod> -- sh to get a shell, kubectl apply -f x.yaml to apply config, kubectl port-forward pod/<pod> 8080:80 to tunnel a port locally.
Inspecting Resources
| Action | Command |
|---|
| List pods | kubectl get pods |
| All namespaces | kubectl get pods -A (--all-namespaces) |
| Everything in a namespace | kubectl get all -n <ns> |
| Nodes | kubectl get nodes |
| Services / ConfigMaps | kubectl get svc / kubectl get configmap |
| Events (sorted) | kubectl get events --sort-by='.lastTimestamp' |
| Details & troubleshooting | kubectl describe pod <pod> |
Logs
| Action | Command |
|---|
| Recent logs | kubectl logs <pod> |
| Follow output | kubectl logs -f <pod> |
| Last N lines | kubectl logs --tail=50 <pod> |
| Last 6 hours | kubectl logs --since=6h <pod> |
| Logs before crash | kubectl logs -p <pod> (--previous) |
| Multi-container: pick one | kubectl logs <pod> -c <container> |
Exec & Debugging
| Action | Command |
|---|
| Shell into a pod | kubectl exec -it <pod> -- sh (use -- bash if available) |
| Run a command in a pod | kubectl exec <pod> -- curl localhost:8080 |
| Copy files | kubectl cp <pod>:/path/file ./local |
| Ephemeral debug container | kubectl debug <pod> -it --image=busybox |
Port Forwarding
| Action | Command |
|---|
| Forward a pod port | kubectl port-forward pod/<pod> 8080:80 |
| Forward a service port | kubectl port-forward svc/<svc> 8080:80 |
Apply & Rollouts
| Action | Command |
|---|
| Apply YAML | kubectl apply -f deploy.yaml |
| Delete resources | kubectl delete -f deploy.yaml / kubectl delete pod <pod> |
| Rolling restart | kubectl rollout restart deploy/<name> |
| Rollout status | kubectl rollout status deploy/<name> |
| Scale | kubectl scale deploy/<name> --replicas=5 |
Context & Namespaces
| Action | Command |
|---|
| Current context | kubectl config current-context |
| List / switch context | kubectl config get-contexts / kubectl config use-context <name> |
| Target a namespace | kubectl get pods -n <ns> (or pin it: kubectl config set-context --current --namespace=<ns>) |
Resource Usage
| Action | Command |
|---|
| Pod usage | kubectl top pods |
| Node usage | kubectl top nodes |
Handy Aliases
alias k='kubectl'
alias kgp='kubectl get pods'
alias kgpa='kubectl get pods -A'
alias kl='kubectl logs'
alias klf='kubectl logs -f'
alias kex='kubectl exec -it'
Sources
- Official kubectl Cheat Sheet (kubernetes.io/docs/reference/kubectl/cheatsheet/)
- Spacelift / Splunk / Last9 kubectl cheatsheets (2026)
最后更新:2026-08-04