กลับไปหน้าสูตร
#kubernetes#kubectl#devops#cheatsheet
Kubernetes kubectl Cheatsheet
รวมคำสั่ง kubectl แบบจัดเต็ม: context, pods, deploy, logs, exec, rollout, troubleshooting และ ops workflow
11 มีนาคม 2569อ่านประมาณ 2 นาที
สารบัญสูตร
Cluster / Context
| Command | ใช้ทำอะไร |
|---|---|
kubectl version --client | ดู client version |
kubectl config get-contexts | ดู contexts |
kubectl config use-context <ctx> | สลับ context |
kubectl cluster-info | ข้อมูล cluster |
kubectl get nodes -o wide | ดู nodes |
Namespace
| Command | ใช้ทำอะไร |
|---|---|
kubectl get ns | ดู namespaces |
kubectl create ns dev | สร้าง namespace |
kubectl config set-context --current --namespace=dev | ตั้ง default namespace |
kubectl delete ns dev | ลบ namespace |
Workloads
| Command | ใช้ทำอะไร |
|---|---|
kubectl get deploy | ดู deployments |
kubectl get pods -o wide | ดู pods |
kubectl get svc | ดู services |
kubectl apply -f k8s/ | apply manifests |
kubectl delete -f k8s/ | delete manifests |
kubectl describe pod <pod> | ดูรายละเอียด pod |
Logs / Exec
| Command | ใช้ทำอะไร |
|---|---|
kubectl logs <pod> | ดู logs |
kubectl logs -f <pod> | follow logs |
kubectl logs <pod> -c <container> | logs container เฉพาะ |
kubectl exec -it <pod> -- sh | เข้า shell |
kubectl cp <pod>:/tmp/a.log ./a.log | copy file จาก pod |
Rollout
| Command | ใช้ทำอะไร |
|---|---|
kubectl rollout status deploy/api | สถานะ rollout |
kubectl rollout history deploy/api | ดู history |
kubectl rollout undo deploy/api | rollback |
kubectl set image deploy/api api=repo/api:v2 | เปลี่ยน image |
kubectl scale deploy/api --replicas=5 | scale replicas |
Port Forward / Debug
| Command | ใช้ทำอะไร |
|---|---|
kubectl port-forward svc/api 8080:80 | forward service port |
kubectl port-forward pod/<pod> 5433:5432 | forward pod port |
kubectl top pod | ดู resource pod |
kubectl top node | ดู resource node |
Selectors & Output
| Command | ใช้ทำอะไร |
|---|---|
kubectl get pods -l app=api | filter by label |
kubectl get pods -A | ทุก namespace |
kubectl get pods -o yaml | output yaml |
kubectl get pods -o jsonpath='{.items[*].metadata.name}' | jsonpath output |
Troubleshooting
| ปัญหา | วิธีเช็ก |
|---|---|
| CrashLoopBackOff | kubectl logs + describe pod |
| ImagePullBackOff | image/tag/registry secret |
| Pending pod | resource requests / node constraints |
| Service เข้าไม่ได้ | endpoints + selector + port mapping |
Production Hygiene
| เรื่อง | แนวทาง |
|---|---|
| แยก namespace ตาม env | dev/staging/prod |
| ใช้ liveness/readiness probes | ลด downtime |
| มี resource requests/limits | ป้องกัน noisy neighbor |
| ใช้ rollout/rollback playbook | recovery เร็ว |