#Kubernetes Commands: คู่มือ kubectl ที่ใช้บ่อยสำหรับ Developer และ DevOps

Kubernetes เป็นแพลตฟอร์มสำหรับจัดการ Containerized Applications แบบอัตโนมัติ ไม่ว่าจะเป็นการ Deploy, Scale, Update หรือ Recover ระบบ เมื่อทำงานกับ Kubernetes เครื่องมือที่ต้องใช้เป็นประจำคือ kubectl

kubectl เป็น Command Line Interface ที่ใช้สื่อสารกับ Kubernetes API Server เพื่อสร้าง ตรวจสอบ แก้ไข และลบ Resources ภายใน Cluster เช่น Pod, Deployment, Service, ConfigMap และ Secret

บทความนี้รวบรวมคำสั่ง Kubernetes ที่ใช้บ่อย พร้อมตัวอย่างที่สามารถนำไปทดลองกับ Minikube, kind, Docker Desktop, DigitalOcean Kubernetes, Amazon EKS, Google GKE หรือ Azure AKS ได้


#สารบัญ

  1. โครงสร้างคำสั่ง kubectl
  2. ตรวจสอบ Cluster
  3. จัดการ Context และ Namespace
  4. ตรวจสอบ Node
  5. จัดการ Pod
  6. จัดการ Deployment
  7. Scale Application
  8. Update และ Rollback Deployment
  9. จัดการ Service
  10. Deploy ด้วย YAML
  11. ดู Logs
  12. เข้าไปทำงานใน Container
  13. Port Forward
  14. ConfigMap และ Secret
  15. Resource Usage
  16. Events
  17. Debug Kubernetes
  18. Labels และ Selectors
  19. Output Formats
  20. คำสั่งที่ควรจำ
  21. Workflow สำหรับ Troubleshooting
  22. Best Practices

#1. โครงสร้างคำสั่ง kubectl

รูปแบบพื้นฐานของคำสั่งคือ

kubectl [command] [TYPE] [NAME] [flags]

ตัวอย่าง

kubectl get pods
kubectl describe pod nginx
kubectl delete pod nginx

คำสั่งที่ใช้บ่อย ได้แก่

Command หน้าที่
get แสดง Resources
describe แสดงรายละเอียด Resource
create สร้าง Resource
apply สร้างหรืออัปเดต Resource จาก YAML
delete ลบ Resource
logs ดู Log
exec รันคำสั่งใน Container
scale ปรับจำนวน Replica
rollout จัดการการ Deploy และ Rollback
port-forward Forward Port มายังเครื่อง Local
top ดู CPU และ Memory Usage
debug ช่วยวิเคราะห์ปัญหา Workload หรือ Node

#คำย่อของ Resources ที่พบบ่อย

Resource คำเต็ม คำย่อ
Pod pods po
Deployment deployments deploy
Service services svc
Namespace namespaces ns
ConfigMap configmaps cm
PersistentVolume persistentvolumes pv
PersistentVolumeClaim persistentvolumeclaims pvc

ตัวอย่าง

kubectl get po
kubectl get deploy
kubectl get svc

#2. ตรวจสอบ Cluster

ตรวจสอบเวอร์ชัน

kubectl version

ตรวจสอบข้อมูล Cluster

kubectl cluster-info

ดู Resources หลัก

kubectl get nodes
kubectl get pods
kubectl get services

ดูทุก Namespace

kubectl get pods -A

หรือ

kubectl get pods --all-namespaces

#3. จัดการ Context และ Namespace

เมื่อทำงานหลาย Cluster เช่น Development, Staging และ Production จำเป็นต้องตรวจสอบ Context ให้ถูกต้องก่อนรันคำสั่ง

ดู Context ทั้งหมด

kubectl config get-contexts

ดู Context ปัจจุบัน

kubectl config current-context

เปลี่ยน Context

kubectl config use-context <context-name>

ตัวอย่าง

kubectl config use-context production

ดู kubeconfig

kubectl config view

#Namespace

ดู Namespace

kubectl get namespaces

หรือ

kubectl get ns

สร้าง Namespace

kubectl create namespace dev

ดู Pod ใน Namespace

kubectl get pods -n dev

กำหนด Namespace เริ่มต้นให้ Context ปัจจุบัน

kubectl config set-context --current --namespace=dev

หลังจากนั้น

kubectl get pods

จะทำงานกับ Namespace dev โดยอัตโนมัติ


#4. ตรวจสอบ Node

ดู Node ทั้งหมด

kubectl get nodes

ดูรายละเอียดเพิ่ม

kubectl get nodes -o wide

ดูรายละเอียด Node

kubectl describe node <node-name>

ตัวอย่าง

kubectl describe node worker-01

ดู CPU และ Memory

kubectl top nodes

kubectl top ต้องอาศัย Metrics API เช่น Metrics Server


#5. จัดการ Pod

Pod เป็นหน่วยพื้นฐานที่เล็กที่สุดสำหรับรัน Container ใน Kubernetes

ดู Pod

kubectl get pods

ดูข้อมูลละเอียดขึ้น

kubectl get pods -o wide

ดู Pod ทุก Namespace

kubectl get pods -A

ดูรายละเอียด Pod

kubectl describe pod <pod-name>

ตัวอย่าง

kubectl describe pod nginx-7c79c4bf97-abcde

ดู YAML ของ Pod

kubectl get pod <pod-name> -o yaml

ลบ Pod

kubectl delete pod <pod-name>

ค้นหา Pod ด้วย Label

kubectl get pods -l app=nginx

#6. จัดการ Deployment

Deployment เหมาะสำหรับจัดการ Stateless Application เช่น Web Application และ REST API

ดู Deployment

kubectl get deployments

หรือ

kubectl get deploy

สร้าง Deployment แบบรวดเร็ว

kubectl create deployment nginx --image=nginx

ดูรายละเอียด

kubectl describe deployment nginx

ดู YAML

kubectl get deployment nginx -o yaml

แก้ไข Deployment

kubectl edit deployment nginx

ลบ Deployment

kubectl delete deployment nginx

#7. Scale Application

สมมติว่า Application มี Deployment ชื่อ web

เพิ่มเป็น 3 Replicas

kubectl scale deployment web --replicas=3

ตรวจสอบ

kubectl get deployment web
kubectl get pods

เพิ่มเป็น 5 Replicas

kubectl scale deployment web --replicas=5

ลดเหลือ 1 Replica

kubectl scale deployment web --replicas=1

#8. Update และ Rollback Deployment

เปลี่ยน Container Image

kubectl set image deployment/nginx nginx=nginx:1.29

ตรวจสอบสถานะ Rollout

kubectl rollout status deployment/nginx

ดูประวัติ

kubectl rollout history deployment/nginx

Rollback กลับ Revision ก่อนหน้า

kubectl rollout undo deployment/nginx

Rollback ไป Revision ที่กำหนด

kubectl rollout undo deployment/nginx --to-revision=2

Restart Deployment

kubectl rollout restart deployment/nginx

คำสั่งนี้มีประโยชน์กรณีต้องการ Restart Pods ภายใต้ Deployment โดยไม่ต้องลบ Pod ทีละตัว


#9. จัดการ Service

Service ช่วยสร้าง Endpoint ที่คงที่สำหรับเข้าถึง Pods

ดู Service

kubectl get services

หรือ

kubectl get svc

สร้าง Service แบบ ClusterIP

kubectl expose deployment nginx   --name=nginx-service   --port=80   --target-port=80

สร้าง NodePort

kubectl expose deployment nginx   --name=nginx-nodeport   --type=NodePort   --port=80

ดูรายละเอียด

kubectl describe service nginx-service

ลบ Service

kubectl delete service nginx-service

#10. Deploy ด้วย YAML

แนวทางที่เหมาะกับระบบจริงคือเก็บ Kubernetes Manifests ไว้ใน Git และ Deploy แบบ Declarative

ตัวอย่าง deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx
          image: nginx:1.29
          ports:
            - containerPort: 80

Deploy

kubectl apply -f deployment.yaml

Deploy หลายไฟล์

kubectl apply -f deployment.yaml -f service.yaml

Deploy ทุก Manifest ใน Directory

kubectl apply -f k8s/

ตรวจสอบความแตกต่างก่อน Apply

kubectl diff -f deployment.yaml

Dry Run

kubectl apply --dry-run=client -f deployment.yaml

ลบ Resource จาก Manifest

kubectl delete -f deployment.yaml

#11. ดู Logs

ดู Log ของ Pod

kubectl logs <pod-name>

ติดตาม Log แบบ Real-time

kubectl logs -f <pod-name>

กรณี Pod มีหลาย Containers

kubectl logs <pod-name> -c <container-name>

ดู Log ของ Container Instance ก่อนหน้า

kubectl logs <pod-name> --previous

ดู Log จาก Deployment

kubectl logs deployment/nginx

ตัวอย่าง

kubectl logs -f deployment/api

#12. เข้าไปทำงานใน Container

เปิด Interactive Shell

kubectl exec -it <pod-name> -- /bin/bash

ถ้า Container ไม่มี Bash

kubectl exec -it <pod-name> -- /bin/sh

รันคำสั่งโดยไม่เปิด Shell

kubectl exec <pod-name> -- ls -la

ดู Environment Variables

kubectl exec <pod-name> -- env

กรณีหลาย Containers

kubectl exec -it <pod-name> -c <container-name> -- /bin/sh

#13. Port Forward

Port Forward เหมาะสำหรับเข้าถึง Service หรือ Application ภายใน Cluster จากเครื่อง Local

Forward ไป Pod

kubectl port-forward pod/<pod-name> 8080:80

Forward ไป Service

kubectl port-forward service/nginx-service 8080:80

Forward ไป Deployment

kubectl port-forward deployment/nginx 8080:80

จากนั้นเปิด

http://localhost:8080

เหมาะสำหรับ

  • ทดสอบ API
  • เปิด Web Application
  • เข้า Database หรือ Dashboard ชั่วคราว
  • Debug ระบบโดยไม่ต้องสร้าง LoadBalancer

#14. ConfigMap และ Secret

#ConfigMap

ดู ConfigMap

kubectl get configmaps

สร้าง ConfigMap

kubectl create configmap app-config   --from-literal=APP_ENV=production

ดูรายละเอียด

kubectl describe configmap app-config

#Secret

ดู Secret

kubectl get secrets

สร้าง Secret

kubectl create secret generic db-secret   --from-literal=username=admin   --from-literal=password=secret123

ดู YAML

kubectl get secret db-secret -o yaml

Secret แบบมาตรฐานใช้ Base64 สำหรับการแทนค่าข้อมูล ไม่ควรมองว่า Base64 เป็น Encryption และไม่ควรเก็บรหัสผ่านจริงลง Git


#15. Resource Usage

ดู CPU และ Memory ของ Node

kubectl top nodes

ดู Pod

kubectl top pods

ดู Pod ใน Namespace

kubectl top pods -n production

ดู Container ภายใน Pod

kubectl top pod <pod-name> --containers

เรียงตาม CPU

kubectl top pod --sort-by=cpu

เรียงตาม Memory

kubectl top pod --sort-by=memory

#16. Events

Events มีประโยชน์มากในการวิเคราะห์ปัญหา Scheduling, Image Pull, Volume และ Container Startup

ดู Events

kubectl get events

เรียงตามเวลา

kubectl get events --sort-by=.metadata.creationTimestamp

ดูใน Namespace

kubectl get events -n production

สถานะที่มักต้องตรวจ Events ได้แก่

Pending
CrashLoopBackOff
ImagePullBackOff
ErrImagePull
CreateContainerConfigError
ContainerCreating

#17. Debug Kubernetes

เมื่อ Pod มีปัญหา ให้เริ่มจาก

kubectl get pods

จากนั้นดูรายละเอียด

kubectl describe pod <pod-name>

ดู Logs

kubectl logs <pod-name>

ถ้า Container Restart ไปแล้ว

kubectl logs <pod-name> --previous

ดู Events

kubectl get events --sort-by=.metadata.creationTimestamp

ตรวจ CPU และ Memory

kubectl top pod <pod-name>

เปิด Shell

kubectl exec -it <pod-name> -- /bin/sh

Kubernetes ยังมี kubectl debug สำหรับสร้าง Debugging Session

kubectl debug <pod-name> -it --image=busybox

Debug Node

kubectl debug node/<node-name> -it --image=busybox

#18. Labels และ Selectors

ดู Labels

kubectl get pods --show-labels

เพิ่ม Label

kubectl label pod nginx environment=production

ค้นหาจาก Label

kubectl get pods -l environment=production

ค้นหาหลายเงื่อนไข

kubectl get pods -l 'environment=production,app=api'

ลบ Label

kubectl label pod nginx environment-

#19. Output Formats

kubectl สามารถแสดง Output ได้หลายรูปแบบ

แบบ Wide

kubectl get pods -o wide

YAML

kubectl get pod <pod-name> -o yaml

JSON

kubectl get pod <pod-name> -o json

เฉพาะชื่อ

kubectl get pods -o name

JSONPath

kubectl get pods -o jsonpath='{.items[*].metadata.name}'

Custom Columns

kubectl get pods   -o custom-columns=NAME:.metadata.name,STATUS:.status.phase

Output แบบ Machine-readable เช่น JSON, YAML และ JSONPath เหมาะสำหรับ Script และ CI/CD Pipeline มากกว่าการ parse ตารางปกติ


#20. คำสั่งที่ควรจำ

หากเพิ่งเริ่ม Kubernetes ให้จำคำสั่งชุดนี้ก่อน

kubectl get pods
kubectl get pods -A
kubectl get pods -o wide

kubectl get deploy
kubectl get svc

kubectl describe pod <pod-name>

kubectl logs <pod-name>
kubectl logs -f <pod-name>

kubectl exec -it <pod-name> -- /bin/sh

kubectl apply -f deployment.yaml
kubectl delete -f deployment.yaml

kubectl scale deployment <name> --replicas=3

kubectl rollout status deployment/<name>
kubectl rollout history deployment/<name>
kubectl rollout undo deployment/<name>

kubectl port-forward service/<service-name> 8080:80

kubectl get events --sort-by=.metadata.creationTimestamp

#21. Workflow สำหรับ Troubleshooting

Workflow ง่าย ๆ สำหรับแก้ปัญหา Application ใน Kubernetes

kubectl get pods
       │
       ▼
ตรวจ STATUS / READY / RESTARTS
       │
       ▼
kubectl describe pod <pod>
       │
       ▼
ตรวจ Events และ Container State
       │
       ▼
kubectl logs <pod>
       │
       ▼
kubectl logs <pod> --previous
       │
       ▼
kubectl get events
       │
       ▼
kubectl top pod <pod>
       │
       ▼
kubectl exec -it <pod> -- /bin/sh

#ตัวอย่างกรณี CrashLoopBackOff

kubectl get pods

สมมติพบ

NAME                     READY   STATUS             RESTARTS
api-77b8d98cdd-x7x2z     0/1     CrashLoopBackOff   6

ตรวจรายละเอียด

kubectl describe pod api-77b8d98cdd-x7x2z

ดู Log

kubectl logs api-77b8d98cdd-x7x2z

ดู Log ก่อน Restart

kubectl logs api-77b8d98cdd-x7x2z --previous

จากนั้นตรวจสอบ

  • Environment Variables
  • Secret
  • ConfigMap
  • Database Connection
  • Application Port
  • Startup Command
  • Liveness Probe
  • Readiness Probe
  • CPU/Memory Limits

#22. Best Practices

#22.1 ใช้ Declarative Configuration

สำหรับ Production ควรใช้

kubectl apply -f k8s/

แทนการสร้าง Resource ด้วย Command Line อย่างเดียว

ข้อดีคือ

  • Version Control ได้
  • Review ผ่าน Pull Request ได้
  • Rollback ง่าย
  • เหมาะกับ CI/CD และ GitOps
  • ลด Configuration Drift

#22.2 ตรวจ Context ก่อนทำงาน Production

kubectl config current-context

ควรตรวจทุกครั้งก่อน delete, apply, scale หรือ rollout


#22.3 ระบุ Namespace ให้ชัดเจน

kubectl get pods -n production

ดีกว่าพึ่งพา Default Namespace เมื่อบริหารหลาย Environment


#22.4 อย่าเก็บ Secret จริงไว้ใน Git

หลีกเลี่ยง

stringData:
  password: super-secret-password

ใน Repository สาธารณะหรือ Repository ที่ไม่มีการควบคุมสิทธิ์เหมาะสม

พิจารณาใช้เครื่องมือ เช่น

  • External Secrets Operator
  • HashiCorp Vault
  • Cloud Secret Manager
  • Sealed Secrets

#22.5 ใช้ GitOps สำหรับระบบที่ใหญ่ขึ้น

เมื่อระบบมี Kubernetes Manifests จำนวนมาก สามารถใช้

Application Repository
        │
        ▼
Docker Image
        │
        ▼
Container Registry
        │
        ▼
GitOps Repository
        │
        ▼
Argo CD / Flux
        │
        ▼
Kubernetes Cluster

แนวทางนี้ทำให้ Git เป็น Source of Truth สำหรับสถานะที่ต้องการของระบบ


#Alias ที่ช่วยให้ใช้งานเร็วขึ้น

สำหรับ Bash หรือ Zsh

alias k=kubectl

จากนั้นใช้

k get pods
k get svc
k get deploy

เพิ่ม Alias

alias kgp='kubectl get pods'
alias kgpa='kubectl get pods -A'
alias kgs='kubectl get svc'
alias kgd='kubectl get deploy'
alias kdp='kubectl describe pod'

#Kubernetes Command Cheat Sheet

งาน Command
ดู Pod kubectl get pods
ดูทุก Namespace kubectl get pods -A
ดู Node kubectl get nodes
ดู Deployment kubectl get deploy
ดู Service kubectl get svc
รายละเอียด Pod kubectl describe pod <pod>
ดู Log kubectl logs <pod>
Follow Log kubectl logs -f <pod>
เข้า Container kubectl exec -it <pod> -- /bin/sh
Apply YAML kubectl apply -f file.yaml
Delete YAML kubectl delete -f file.yaml
Scale kubectl scale deployment <name> --replicas=3
Restart kubectl rollout restart deployment/<name>
Rollback kubectl rollout undo deployment/<name>
Port Forward kubectl port-forward svc/<name> 8080:80
Events kubectl get events
CPU/Memory kubectl top pods
Debug kubectl debug <pod> -it --image=busybox

#สรุป

การทำงานกับ Kubernetes ไม่จำเป็นต้องจำคำสั่งทั้งหมด แต่ควรเข้าใจ Workflow ของ kubectl

กลุ่มคำสั่งที่ควรใช้งานให้คล่องที่สุดคือ

get
describe
logs
exec
apply
delete
scale
rollout
port-forward
top
debug

สำหรับ Developer การใช้ get, describe, logs, exec และ port-forward จะช่วยในการตรวจสอบ Application ได้มาก

สำหรับ DevOps และ Platform Engineer ควรเพิ่มความเข้าใจเรื่อง apply, rollout, scale, Namespace, Context, Resource Usage และ GitOps

เมื่อระบบเข้าสู่ Production ควรเก็บ Kubernetes Configuration ไว้ใน Git ใช้ Declarative Configuration และสร้างกระบวนการ Deployment ผ่าน CI/CD หรือ GitOps เพื่อให้การเปลี่ยนแปลงสามารถตรวจสอบและย้อนกลับได้ง่าย


#เอกสารอ้างอิง