กลับไปหน้าสูตร
#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.logcopy file จาก pod

Rollout

Commandใช้ทำอะไร
kubectl rollout status deploy/apiสถานะ rollout
kubectl rollout history deploy/apiดู history
kubectl rollout undo deploy/apirollback
kubectl set image deploy/api api=repo/api:v2เปลี่ยน image
kubectl scale deploy/api --replicas=5scale replicas

Port Forward / Debug

Commandใช้ทำอะไร
kubectl port-forward svc/api 8080:80forward service port
kubectl port-forward pod/<pod> 5433:5432forward pod port
kubectl top podดู resource pod
kubectl top nodeดู resource node

Selectors & Output

Commandใช้ทำอะไร
kubectl get pods -l app=apifilter by label
kubectl get pods -Aทุก namespace
kubectl get pods -o yamloutput yaml
kubectl get pods -o jsonpath='{.items[*].metadata.name}'jsonpath output

Troubleshooting

ปัญหาวิธีเช็ก
CrashLoopBackOffkubectl logs + describe pod
ImagePullBackOffimage/tag/registry secret
Pending podresource requests / node constraints
Service เข้าไม่ได้endpoints + selector + port mapping

Production Hygiene

เรื่องแนวทาง
แยก namespace ตาม envdev/staging/prod
ใช้ liveness/readiness probesลด downtime
มี resource requests/limitsป้องกัน noisy neighbor
ใช้ rollout/rollback playbookrecovery เร็ว