Kubernetes
ระบบจัดการ container orchestration ที่ช่วยให้จัดการ container หลายตัวใน cluster ได้อย่างมีประสิทธิภาพ รองรับการ scale, deploy, และ manage applications อัตโนมัติ
Resource Creation Snippets
Section titled “Resource Creation Snippets”สร้าง resource จาก YAML ด้วย kubectl apply โดยแต่ละ snippet สามารถแยกเป็นไฟล์แล้วนำไปใช้ได้ทันที
Pod เหมาะสำหรับการทดลองหรือ workload ที่ไม่ต้องการ rolling update และ self-healing แบบ Deployment
apiVersion: v1kind: Podmetadata: name: nginx-pod labels: app: nginxspec: containers: - name: nginx image: nginx:1.27 ports: - containerPort: 80# สร้าง Podkubectl apply -f pod.yaml
# ตรวจสอบ Pod และดูรายละเอียดkubectl get pod nginx-podkubectl describe pod nginx-pod
# ลบ Podkubectl delete -f pod.yamlDeployment
Section titled “Deployment”Deployment เหมาะสำหรับ application ที่ต้องการ replicas, rolling update และ self-healing
apiVersion: apps/v1kind: Deploymentmetadata: name: nginxspec: replicas: 2 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.27 env: - name: APP_ENV value: production - name: API_URL valueFrom: configMapKeyRef: name: app-config key: api-url - name: DATABASE_PASSWORD valueFrom: secretKeyRef: name: app-secret key: database-password resources: requests: cpu: 100m memory: 128Mi limits: cpu: 500m memory: 512Mi ports: - containerPort: 80โครงสร้าง spec ของ Deployment มีส่วนสำคัญดังนี้:
spec.replicasและspec.selector— กำหนดจำนวน replicas และบอกว่า Deployment จะดูแล Pod ไหนspec.template— template สำหรับสร้าง Pod ใหม่ โดย label ต้องตรงกับselector.matchLabelsspec.template.spec— กำหนดรายละเอียดของ Pod เช่นcontainers,volumesและserviceAccountNamespec.template.spec.containers[].env— กำหนด environment variables ให้ container แต่ละตัวspec.template.spec.containers[].resources— กำหนด resource ที่ container ขอใช้และใช้ได้สูงสุด
requests ใช้ให้ Kubernetes เลือก Node ที่มี resource เพียงพอ ส่วน limits ใช้จำกัดการใช้งานสูงสุดของ container หากใช้ memory เกิน limit อาจถูก OOMKilled และถ้าใช้ CPU เกิน limit จะถูก throttle
ค่าใน env มีได้หลายรูปแบบ:
env: # ค่าแบบเขียนตรง ๆ เหมาะกับค่าที่ไม่ sensitive - name: APP_ENV value: production
# อ่านค่าจาก ConfigMap - name: API_URL valueFrom: configMapKeyRef: name: app-config key: api-url
# อ่านค่าจาก Secret ห้ามใส่ password ตรง ๆ ใน Deployment YAML - name: DATABASE_PASSWORD valueFrom: secretKeyRef: name: app-secret key: database-passwordถ้าต้องการโหลดทุก key จาก ConfigMap หรือ Secret เป็น environment variables ให้ใช้ envFrom แทน env:
spec: template: spec: containers: - name: nginx image: nginx:1.27 envFrom: - configMapRef: name: app-config - secretRef: name: app-secret# สร้างหรืออัปเดต Deploymentkubectl apply -f deployment.yaml
# รอให้ rollout เสร็จkubectl rollout status deployment/nginx
# ตรวจสอบ Pods ที่ Deployment ดูแลkubectl get deployment,pods -l app=nginx
# ลบ Deploymentkubectl delete -f deployment.yamlService
Section titled “Service”Service ใช้เปิด endpoint ให้ Pod อื่นหรือผู้ใช้งานเข้าถึง โดย selector ต้องตรงกับ label ของ Pod
apiVersion: v1kind: Servicemetadata: name: nginxspec: type: ClusterIP selector: app: nginx ports: - name: http port: 80 targetPort: 80# สร้าง Servicekubectl apply -f service.yaml
# ตรวจสอบ Service และ endpointskubectl get svc nginxkubectl get endpoints nginx
# ทดสอบจากเครื่อง localkubectl port-forward svc/nginx 8080:80
# ลบ Servicekubectl delete -f service.yamlNodePort — เปิดผ่าน port ของ Node (ช่วง 30000-32767) เหมาะกับ cluster ที่ยังไม่มี LoadBalancer
apiVersion: v1kind: Servicemetadata: name: nginx-nodeportspec: type: NodePort selector: app: nginx ports: - name: http port: 80 targetPort: 80 nodePort: 30080# เข้าถึงผ่าน IP ของ Node ใด Node หนึ่งcurl http://<node-ip>:30080LoadBalancer — ให้ cloud provider สร้าง external load balancer ให้อัตโนมัติ เหมาะกับการเปิด traffic จากภายนอก cluster
apiVersion: v1kind: Servicemetadata: name: nginx-lbspec: type: LoadBalancer selector: app: nginx ports: - name: http port: 80 targetPort: 80# รอจนได้ external IPkubectl get svc nginx-lb -w
# ทดสอบจากภายนอกcurl http://<external-ip>Headless — ตั้ง clusterIP: None เพื่อไม่สร้าง virtual IP และไม่ทำ load balancing แต่จะ return IP ของ Pod ทุกตัวผ่าน DNS แทน เหมาะกับ StatefulSet ที่ต้องติดต่อ Pod ตรง ๆ เช่น database cluster
apiVersion: v1kind: Servicemetadata: name: postgres-headlessspec: clusterIP: None selector: app: postgres ports: - name: postgres port: 5432 targetPort: 5432# DNS จะ resolve เป็น IP ของ Pod ทุกตัว ไม่ใช่ IP เดียวnslookup postgres-headless
# เข้าถึง Pod เฉพาะตัวของ StatefulSet ผ่าน pattern <pod-name>.<service-name>nslookup postgres-0.postgres-headlesspostgres-0, postgres-1) ทำให้ client เลือกติดต่อ Pod ใด Pod หนึ่งได้โดยตรง ไม่ผ่าน load balancing ConfigMap
Section titled “ConfigMap”ใช้เก็บ configuration ที่ไม่เป็นความลับ และนำไปใช้เป็น environment variables หรือ file ได้
apiVersion: v1kind: ConfigMapmetadata: name: app-configdata: APP_ENV: production LOG_LEVEL: info app.properties: | feature.new-ui=true http.timeout=30s# สร้าง ConfigMapkubectl apply -f configmap.yaml
# ตรวจสอบค่าใน ConfigMapkubectl get configmap app-config -o yaml
# ลบ ConfigMapkubectl delete -f configmap.yamlSecret
Section titled “Secret”ใช้เก็บข้อมูล sensitive เช่น password, token หรือ API key โดยใช้ stringData เพื่อให้เขียนค่า plain text ใน manifest ได้ง่าย
apiVersion: v1kind: Secretmetadata: name: app-secrettype: OpaquestringData: DATABASE_USER: app DATABASE_PASSWORD: change-me API_TOKEN: replace-me# สร้าง Secretkubectl apply -f secret.yaml
# ตรวจสอบ metadata โดยไม่แสดงค่า secretkubectl get secret app-secret
# อ่านค่าและ decode เฉพาะ key ที่ต้องการkubectl get secret app-secret -o jsonpath='{.data.DATABASE_PASSWORD}' | base64 -d
# ลบ Secretkubectl delete -f secret.yaml
Secretที่เก็บใน Kubernetes เป็น Base64 encoding ไม่ใช่ encryption โดยอัตโนมัติ หลีกเลี่ยงการ commit ค่า secret จริงลง Git
Volume ใน Pod
Section titled “Volume ใน Pod”ตัวอย่างด้านล่างเป็น snippets ที่พบบ่อยสำหรับเพิ่ม volume และ volumeMounts ใน spec ของ Pod หรือ Deployment template
emptyDir สำหรับ temporary storage
Section titled “emptyDir สำหรับ temporary storage”ข้อมูลอยู่ตลอดอายุของ Pod และจะหายเมื่อ Pod ถูกลบหรือย้ายไป Node ใหม่
apiVersion: v1kind: Podmetadata: name: emptydir-demospec: containers: - name: app image: nginx:1.27 volumeMounts: - name: cache mountPath: /var/cache/app volumes: - name: cache emptyDir: {}emptyDir แบบใช้ memory
Section titled “emptyDir แบบใช้ memory”เหมาะกับ cache ชั่วคราวที่ต้องการความเร็ว แต่ใช้ RAM ของ Node และควรกำหนดขนาดจำกัด
volumes: - name: memory-cache emptyDir: medium: Memory sizeLimit: 256MihostPath สำหรับ mount directory จาก Node
Section titled “hostPath สำหรับ mount directory จาก Node”ใช้เฉพาะกรณีที่จำเป็นจริง ๆ เพราะ Pod จะผูกกับ filesystem ของ Node และอาจมีปัญหาเมื่อย้าย Node
volumes: - name: node-data hostPath: path: /var/lib/my-app type: DirectoryOrCreateMount ConfigMap เป็น file
Section titled “Mount ConfigMap เป็น file”volumes: - name: app-config configMap: name: app-config items: - key: app.properties path: app.propertiesvolumeMounts: - name: app-config mountPath: /etc/my-app/app.properties subPath: app.properties readOnly: trueMount Secret เป็น file
Section titled “Mount Secret เป็น file”volumes: - name: app-secret secret: secretName: app-secret defaultMode: 0400volumeMounts: - name: app-secret mountPath: /etc/my-app/secrets readOnly: trueใช้ PVC เป็น persistent storage
Section titled “ใช้ PVC เป็น persistent storage”PVC เป็นวิธีมาตรฐานสำหรับขอ storage ที่ยังอยู่แม้ Pod ถูกสร้างใหม่ โดย storageClassName ต้องตรงกับ StorageClass ใน cluster
แบบทั่วไปให้ใช้ PVC ขอ storage จาก StorageClass ที่มีอยู่ใน cluster:
apiVersion: v1kind: PersistentVolumeClaimmetadata: name: app-dataspec: accessModes: - ReadWriteOnce storageClassName: standard resources: requests: storage: 1Giถ้า cluster ไม่มี dynamic provisioning สามารถสร้าง PV เองแล้วให้ PVC bind ด้วย storageClassName และขนาดที่ตรงกันได้:
apiVersion: v1kind: PersistentVolumemetadata: name: app-data-pvspec: capacity: storage: 5Gi accessModes: - ReadWriteOnce persistentVolumeReclaimPolicy: Retain storageClassName: manual hostPath: path: /mnt/data/appapiVersion: v1kind: PersistentVolumeClaimmetadata: name: app-dataspec: accessModes: - ReadWriteOnce storageClassName: manual resources: requests: storage: 1Gi
hostPathเหมาะกับ local cluster หรือ lab เท่านั้น สำหรับ production ควรใช้ StorageClass และ CSI driver ของ cloud หรือ storage platform
volumeMounts: - name: app-data mountPath: /var/lib/my-app
volumes: - name: app-data persistentVolumeClaim: claimName: app-data# สร้าง PVCkubectl apply -f pvc.yaml
# ตรวจสอบสถานะ PVC และ PV ที่ถูก bindkubectl get pvc,pv
# ลบ PVC เมื่อไม่ต้องการใช้แล้วkubectl delete -f pvc.yamlMount เฉพาะ file ด้วย subPath
Section titled “Mount เฉพาะ file ด้วย subPath”ใช้เมื่อต้องการ mount key เดียวจาก ConfigMap หรือ Secret โดยไม่ทับทั้ง directory
volumeMounts: - name: app-config mountPath: /etc/my-app/app.properties subPath: app.properties readOnly: trueFile ที่ mount ด้วย
subPathจะไม่รับการ update จาก ConfigMap หรือ Secret โดยอัตโนมัติ ต้อง restart Pod หลังแก้ค่า
รวมหลาย source ด้วย projected
Section titled “รวมหลาย source ด้วย projected”รวม ConfigMap, Secret และ Downward API ไว้ใน directory เดียว
volumes: - name: runtime-config projected: sources: - configMap: name: app-config - secret: name: app-secret - downwardAPI: items: - path: pod-name fieldRef: fieldPath: metadata.nameตัวอย่างการนำ volume ไปใช้ใน Deployment:
apiVersion: apps/v1kind: Deploymentmetadata: name: appspec: replicas: 1 selector: matchLabels: app: app template: metadata: labels: app: app spec: containers: - name: app image: nginx:1.27 volumeMounts: - name: runtime-config mountPath: /etc/my-app readOnly: true volumes: - name: runtime-config projected: sources: - configMap: name: app-config - secret: name: app-secret# ตรวจสอบ volume mount จากใน containerkubectl exec deploy/app -- ls -la /etc/my-app
# ดูรายละเอียด volume และ mount configurationkubectl describe pod -l app=appPod คือ smallest deployable unit ใน Kubernetes โดยแต่ละ Pod จะ contain หนึ่งหรือหลาย containers ที่ใช้ shared storage และ network
# แสดง pods ทั้งหมดใน namespace ปัจจุบันkubectl get pods
# แสดง pods พร้อม detail เพิ่มเติมkubectl get pods -o wide
# แสดง pods ทั้งหมดในทุก namespacekubectl get pods --all-namespaces
# ดูข้อมูล detail ของ podkubectl describe pod <pod-name>
# ดู logs ของ podkubectl logs <pod-name>
# ดู logs แบบ followkubectl logs -f <pod-name>
# exec เข้าไปใน containerkubectl exec -it <pod-name> -- /bin/sh
# ลบ podkubectl delete pod <pod-name>Deployment
Section titled “Deployment”Deployment คือ abstraction layer ที่อยู่บน Pod ช่วยให้จัดการ scaling, rolling updates, และ rollback ได้ง่ายขึ้น
# แสดง deployments ทั้งหมดkubectl get deployments
# ดูข้อมูล detail ของ deploymentkubectl describe deployment <deployment-name>
# สร้าง deployment จาก yaml filekubectl apply -f <deployment.yaml>
# ดู rollout statuskubectl rollout status deployment/<deployment-name>
# rollback deployment กลับไป version ก่อนหน้าkubectl rollout undo deployment/<deployment-name>
# ดู history ของ rolloutkubectl rollout history deployment/<deployment-name>Health Probes
Section titled “Health Probes”สำหรับ PostgreSQL ให้ใช้ pg_isready ตรวจสอบว่า database พร้อมรับ connection หรือยัง โดยวาง probes ไว้ภายใน containers[] ของ Pod หรือ Deployment template
containers: - name: postgres image: postgres:17 env: - name: POSTGRES_USER valueFrom: secretKeyRef: name: postgres-secret key: username - name: POSTGRES_DB value: app livenessProbe: exec: command: - sh - -c - pg_isready -U "$POSTGRES_USER" -d "$POSTGRES_DB" initialDelaySeconds: 15 periodSeconds: 10 timeoutSeconds: 5 failureThreshold: 6 readinessProbe: exec: command: - sh - -c - pg_isready -U "$POSTGRES_USER" -d "$POSTGRES_DB" initialDelaySeconds: 5 periodSeconds: 5 timeoutSeconds: 5 failureThreshold: 3livenessProbeใช้ตรวจว่า PostgreSQL ยังทำงานอยู่หรือไม่ ถ้าล้มเหลวต่อเนื่อง Kubernetes จะ restart containerreadinessProbeใช้ตรวจว่า PostgreSQL พร้อมรับ traffic หรือไม่ ถ้ายังไม่พร้อม Pod จะไม่ถูกส่ง traffic จาก Service
POSTGRES_USER และ POSTGRES_DB ต้องมีอยู่ใน environment ของ container ก่อน จึงจะใช้ในคำสั่ง pg_isready ได้ Scaling
Section titled “Scaling”# scale deployment ไปที่จำนวน replicas ที่ต้องการkubectl scale deployment <deployment-name> --replicas=3
# scale แบบ horizontal pod autoscalerkubectl autoscale deployment <deployment-name> --min=2 --max=10 --cpu-percent=80ReplicaSet
Section titled “ReplicaSet”# แสดง replicasets ทั้งหมดkubectl get replicasets
# ดูข้อมูล detail ของ replicasetkubectl describe replicaset <replicaset-name>Services
Section titled “Services”Service คือ abstraction ที่ defines logical set of pods และ policy สำหรับเข้าถึง pods นั้นๆ
# แสดง services ทั้งหมดkubectl get serviceskubectl get svc
# ดูข้อมูล detail ของ servicekubectl describe service <service-name>
# สร้าง service แบบ LoadBalancerkubectl expose deployment <deployment-name> --port=80 --type=LoadBalancer
# สร้าง service แบบ ClusterIP (internal)kubectl expose deployment <deployment-name> --port=80 --type=ClusterIP
# สร้าง service แบบ NodePortkubectl expose deployment <deployment-name> --port=80 --type=NodePortPort Forwarding
Section titled “Port Forwarding”# forward port จาก local ไปยัง podkubectl port-forward pod/<pod-name> 8080:80
# forward port จาก local ไปยัง servicekubectl port-forward svc/<service-name> 8080:80ConfigMaps
Section titled “ConfigMaps”ConfigMap ใช้เก็บ configuration ที่ไม่เป็น secret เช่น environment variables, command-line arguments, config files
# สร้าง configmap จาก literalkubectl create configmap <configmap-name> --from-literal=key=value
# สร้าง configmap จาก filekubectl create configmap <configmap-name> --from-file=<file-path>
# สร้าง configmap จาก env filekubectl create configmap <configmap-name> --from-env-file=<env-file-path>
# ดู configmapkubectl get configmapskubectl describe configmap <configmap-name>Secrets
Section titled “Secrets”Secret ใช้เก็บข้อมูลที่ sensitive เช่น passwords, tokens, keys
# สร้าง secret จาก literalkubectl create secret generic <secret-name> --from-literal=key=value
# สร้าง secret จาก filekubectl create secret generic <secret-name> --from-file=<file-path>
# สร้าง secret แบบ docker registrykubectl create secret docker-registry <secret-name> --docker-server=<server> --docker-username=<user> --docker-password=<pass>
# ดู secretskubectl get secrets
# ดู secret value (base64 decode)kubectl get secret <secret-name> -o jsonpath='{.data.key}' | base64 -dใช้ kubectl edit แก้ Secret
Section titled “ใช้ kubectl edit แก้ Secret”kubectl edit ใช้แก้ Secret ได้ เหมาะกับการแก้เร่งด่วน แต่ค่าที่เปิดขึ้นมาจะอยู่ใน data และต้องเป็น Base64 ไม่ใช่ plaintext:
# ตรวจสอบ cluster และเปิด Secret ใน editorkubectl config current-contextkubectl edit secret one-id-secret -n productionใน editor แก้ค่าของ key ใต้ data: หรือเอาบรรทัดของ key ออกเพื่อลบ key นั้น แล้ว save และปิด editor ควรหลีกเลี่ยงการคัดลอกหรือถ่ายภาพหน้าจอที่มีค่า Secret
ถ้าต้องการใส่ plaintext โดยไม่ encode เอง ให้ใช้ kubectl patch กับไฟล์ชั่วคราวที่มี permission จำกัด:
# สร้างไฟล์โดยจำกัดสิทธิ์ให้อ่าน/เขียนได้เฉพาะเจ้าของumask 077${EDITOR:-vi} secret-patch.yaml# secret-patch.yaml — ระบุเฉพาะ key ที่ต้องการเปลี่ยนstringData: DATABASE_URL: "postgresql://user:password@host:5432/db"# แก้เฉพาะ key ที่ระบุ โดยไม่กระทบ key อื่นkubectl patch secret one-id-secret -n production --type merge --patch-file secret-patch.yaml
# ลบไฟล์ชั่วคราวหลังใช้งานrm secret-patch.yamlลบ key ด้วย kubectl patch ได้เช่นกัน:
# ลบ key API_TOKEN ออกจาก Secretkubectl patch secret one-id-secret -n production --type merge -p '{"data":{"API_TOKEN":null}}'ถ้า Deployment ใช้ Secret เป็น environment variable ให้ restart เพื่อให้ Pod ใหม่รับค่า และตรวจสอบ rollout กับ health check หลังแก้:
# Restart Deployment และรอให้ rollout เสร็จkubectl rollout restart deployment/one-id-service -n productionkubectl rollout status deployment/one-id-service -n productionSecret ที่ mount เป็น volume ปกติจะทยอยอัปเดต แต่
subPathและ environment variables ไม่อัปเดตใน Pod เดิม ส่วน K9s เหมาะกับการตรวจสอบ Secret/Pod
สำหรับการใช้งานระยะยาว ควรจัดการ Secret ผ่าน External Secrets หรือ Secret Manager แทนการแก้ใน cluster โดยตรง
Namespaces
Section titled “Namespaces”Namespace ช่วยให้แบ่ง cluster ออกเป็นหลาย virtual clusters
# แสดง namespaces ทั้งหมดkubectl get namespaceskubectl get ns
# สร้าง namespacekubectl create namespace <namespace-name>
# เปลี่ยน namespace ปัจจุบันkubectl config set-context --current --namespace=<namespace-name>
# แสดง resources ใน namespace ที่ระบุkubectl get pods -n <namespace-name>Ingress
Section titled “Ingress”# แสดง ingresses ทั้งหมดkubectl get ingress
# ดู ingress detailkubectl describe ingress <ingress-name>
# apply ingress from yamlkubectl apply -f <ingress.yaml># แสดง nodes ทั้งหมดkubectl get nodes
# ดูข้อมูล detail ของ nodekubectl describe node <node-name>
# แสดง node resource usagekubectl top nodesEvents
Section titled “Events”# แสดง events ทั้งหมด sort by timekubectl get events --sort-by='.lastTimestamp'
# แสดง events ใน namespace ที่ระบุkubectl get events -n <namespace-name>
# แสดง events แบบ watchkubectl get events --watchLogging & Debugging
Section titled “Logging & Debugging”# แสดง pods ที่มีปัญหาkubectl get pods | grep -v Running
# ดู logs ของ pod ที่มีหลาย containerskubectl logs <pod-name> -c <container-name>
# ดู logs จาก previous container instance (ถ้า container restart แล้ว)kubectl logs <pod-name> --previous
# describe pod ดูสาเหตุkubectl describe pod <pod-name>
# เข้าไปใน container เพื่อ debugkubectl exec -it <pod-name> -c <container-name> -- /bin/sh
# ตรวจสอบ endpointkubectl get endpoints <service-name>Resources
Section titled “Resources”# แสดง resources ทั้งหมดใน clusterkubectl api-resources
# แสดง resources ที่มีใน namespacekubectl api-resources --namespaced=true
# แสดง resources ที่ไม่มีใน namespace (cluster-wide)kubectl api-resources --namespaced=false
# แสดง API version ของ resourcekubectl api-resources -o wideYAML Operations
Section titled “YAML Operations”# แสดง yaml ของ resource (ไม่ apply)kubectl get pod <pod-name> -o yaml
# สร้าง resource จาก yamlkubectl apply -f <file.yaml>
# สร้างหลาย resources จาก directorykubectl apply -f <directory>/
# ลบ resource จาก yamlkubectl delete -f <file.yaml>
# ดู difference ก่อน applykubectl diff -f <file.yaml>Context & Configuration
Section titled “Context & Configuration”# แสดง contexts ทั้งหมดkubectl config get-contexts
# เปลี่ยน contextkubectl config use-context <context-name>
# แสดง current contextkubectl config current-context
# แสดง clusters ทั้งหมดkubectl config get-clusters
# ดู config ทั้งหมดkubectl config viewKubernetes Environment Isolation
Section titled “Kubernetes Environment Isolation”แยก kubeconfig ของแต่ละ environment และบังคับให้เข้า shell ของ environment ก่อนใช้ kubectl ช่วยลดโอกาสส่งคำสั่งไปผิด cluster โดยจะแสดง label และสีของ environment ไว้ใน prompt
แยกที่เก็บ kubeconfig
Section titled “แยกที่เก็บ kubeconfig”# สร้าง directory สำหรับเก็บ kubeconfig แยกตาม environmentmkdir -p ~/.kube/envs
# จำกัดสิทธิ์ให้มีเฉพาะ user เจ้าของ directorychmod 700 ~/.kube/envs
# สร้างหรือนำ kubeconfig ของแต่ละ environment มาเก็บไว้ในไฟล์ที่เกี่ยวข้องnano ~/.kube/envs/prod.yaml
# จำกัดสิทธิ์ของ kubeconfig ไม่ให้ user อื่นอ่านได้chmod 600 ~/.kube/envs/prod.yamlโครงสร้างไฟล์ที่แนะนำ:
~/.kube/envs/├── dev.yaml├── uat.yaml└── prod.yamlทดสอบ kubeconfig โดยระบุไฟล์โดยตรงก่อนนำไปใช้กับ shell function:
# ตรวจสอบว่า kubeconfig ของ production เชื่อมต่อ cluster ได้kubectl --kubeconfig ~/.kube/envs/prod.yaml get nodesถ้าแสดงรายการ nodes ได้ แสดงว่า kubeconfig ใช้งานได้
สร้าง Environment Shell
Section titled “สร้าง Environment Shell”เพิ่ม function เหล่านี้ใน ~/.zshrc เพื่อเปิด subshell ที่กำหนด kubeconfig และ label ให้ตรงกับ environment:
# เปิด subshell สำหรับ Developmentfunction kube-dev() { KUBECONFIG="$HOME/.kube/envs/dev.yaml" \ KUBE_ENV="DEV" \ KUBE_LABEL="DEVELOPMENT" \ zsh}
# เปิด subshell สำหรับ UATfunction kube-uat() { KUBECONFIG="$HOME/.kube/envs/uat.yaml" \ KUBE_ENV="UAT" \ KUBE_LABEL="UAT" \ zsh}
# เปิด subshell สำหรับ Productionfunction kube-prod() { KUBECONFIG="$HOME/.kube/envs/prod.yaml" \ KUBE_ENV="PROD" \ KUBE_LABEL="PRODUCTION" \ zsh}เพิ่ม prompt สำหรับแยก environment:
# แสดงสีและ label ของ environment ใน promptif [[ "$KUBE_ENV" == "PROD" ]]; then PROMPT='%F{red}[PRODUCTION]%f %~ %# 'elif [[ "$KUBE_ENV" == "UAT" ]]; then PROMPT='%F{yellow}[UAT]%f %~ %# 'elif [[ "$KUBE_ENV" == "DEV" ]]; then PROMPT='%F{green}[DEVELOPMENT]%f %~ %# 'fiตรวจ syntax และโหลด configuration ใหม่:
# ตรวจสอบ syntax ของ zsh configuration โดยไม่ executezsh -n ~/.zshrc
# โหลด zsh configuration ใหม่source ~/.zshrcเข้าและออกจาก Environment
Section titled “เข้าและออกจาก Environment”เปิด shell ของ environment ที่ต้องการก่อนใช้คำสั่ง Kubernetes:
# เข้า Development environmentkube-dev
# หรือเข้า UAT / Production environmentkube-uatkube-prodเมื่อเข้า kube-prod แล้ว prompt จะแสดง label สีแดง เช่น [PRODUCTION] ~ % คำสั่งต่อไปนี้จะใช้ ~/.kube/envs/prod.yaml:
# ตรวจสอบ nodes ใน production clusterkubectl get nodes
# ตรวจสอบ pods ทุก namespacekubectl get pods -A
# แสดง Helm releases ทุก namespacehelm list -A
# เปิด k9s ด้วย kubeconfig ของ environment นี้k9s
# ตรวจสอบ kubeconfig และ context ที่กำลังใช้งานecho $KUBECONFIGkubectl config current-contextออกจาก environment shell เพื่อกลับไปยัง shell ปกติ:
# ปิด subshell และคืนสู่ shell เดิมexitหลัง exit ค่า KUBECONFIG, KUBE_ENV และ KUBE_LABEL ที่กำหนดให้ subshell จะไม่ติดกลับไปยัง shell ปกติ
~/.kube/config หากไม่จำเป็น เพราะการแยกไฟล์ช่วยลดโอกาสยิงคำสั่งผิด cluster ได้มากขึ้น Common Options
Section titled “Common Options”# -n : ระบุ namespacekubectl get pods -n <namespace>
# -o : กำหนด output format (yaml, json, wide)kubectl get pods -o yamlkubectl get pods -o jsonkubectl get pods -o wide
# -l : filter ด้วย labelkubectl get pods -l app=myapp
# -f : ระบุ filenamekubectl apply -f deployment.yaml
# --dry-run : ทดสอบคำสั่งโดยไม่ applykubectl apply -f deployment.yaml --dry-run
# -w : watch modekubectl get pods -wCheat Sheet Quick Reference
Section titled “Cheat Sheet Quick Reference”| คำสั่ง | คำอธิบาย |
|---|---|
kubectl get pods | แสดง pods ทั้งหมด |
kubectl get svc | แสดง services ทั้งหมด |
kubectl get ns | แสดง namespaces ทั้งหมด |
kubectl get all | แสดง resources หลักทั้งหมด |
kubectl apply -f | apply yaml file |
kubectl delete -f | delete จาก yaml file |
kubectl describe | ดู detail ของ resource |
kubectl logs | ดู logs ของ pod |
kubectl exec | exec เข้า container |
kubectl port-forward | forward port |
kubectl scale | scale deployment |
kubectl rollout | manage rollout |
kubectl top | ดู resource usage |
kubectl config | จัดการ kubeconfig |
kubectl api-resources | แสดง resource types ทั้งหมด |