Cơ Bản kubectl
Thông Tin Cluster
kubectl cluster-info kubectl get nodes kubectl config current-context kubectl config use-context my-cluster
Lệnh Thiết Yếu
kubectl get <resource>Liệt kê tài nguyên
kubectl describe <resource> <name>Thông tin chi tiết tài nguyên
kubectl create -f file.yamlTạo tài nguyên từ file
kubectl apply -f file.yamlTạo hoặc cập nhật tài nguyên
kubectl delete -f file.yamlXóa tài nguyên từ file
kubectl edit <resource> <name>Chỉnh sửa tài nguyên tại chỗ
kubectl api-resourcesLiệt kê tất cả loại tài nguyên
Định Dạng Output
-o wideThêm cột (IP, node)
-o yamlOutput YAML đầy đủ
-o jsonOutput JSON đầy đủ
-o jsonpath='{.spec}'Trích xuất trường cụ thể
--sort-by=.metadata.nameSắp xếp output theo trường
Pods
Thao Tác Pod
kubectl get pods kubectl get pods -A # all namespaces kubectl run nginx --image=nginx # quick pod kubectl delete pod nginx
Pod YAML
apiVersion: v1 kind: Pod metadata: name: myapp labels: { app: myapp } spec: containers: - name: app image: nginx:1.27 ports: - containerPort: 80
Giá Trị Trạng Thái Pod
RunningTất cả container đã khởi động
PendingChờ scheduling hoặc pull image
CrashLoopBackOffContainer liên tục crash và khởi động lại
ImagePullBackOffKhông thể pull container image
CompletedĐã chạy xong (Jobs)
Deployments
Deployment YAML
apiVersion: apps/v1 kind: Deployment metadata: name: web spec: replicas: 3 selector: matchLabels: { app: web } template: metadata: labels: { app: web } spec: containers: - name: web image: nginx:1.27 ports: - containerPort: 80
Lệnh Deployment
kubectl get deployLiệt kê deployments
kubectl scale deploy web --replicas=5Scale replicas
kubectl set image deploy/web web=nginx:1.28Cập nhật image (rolling)
kubectl rollout status deploy/webTheo dõi tiến trình rollout
kubectl rollout undo deploy/webRollback về phiên bản trước
kubectl rollout history deploy/webXem lịch sử phiên bản
Services
Loại Service
ClusterIPChỉ nội bộ (mặc định)
NodePortExpose trên IP mỗi node tại port cố định
LoadBalancerLoad balancer bên ngoài (cloud)
ExternalNameAlias DNS đến service bên ngoài
Service YAML
apiVersion: v1 kind: Service metadata: name: web-svc spec: type: ClusterIP selector: { app: web } ports: - port: 80 targetPort: 80
Expose Nhanh
kubectl expose deploy web --port=80 --type=ClusterIP kubectl expose deploy web --port=80 --type=NodePort kubectl get svc
ConfigMaps & Secrets
ConfigMap
kubectl create configmap app-cfg \ --from-literal=DB_HOST=db.example.com \ --from-file=config.ini
Secret
kubectl create secret generic db-creds \ --from-literal=username=admin \ --from-literal=password=s3cret
Dùng Trong Pods
# As environment variables envFrom: - configMapRef: { name: app-cfg } - secretRef: { name: db-creds } # As volume mount volumes: - name: cfg configMap: { name: app-cfg }
Lệnh
kubectl get cmLiệt kê ConfigMaps
kubectl get secretLiệt kê Secrets
kubectl describe cm app-cfgHiển thị dữ liệu ConfigMap
kubectl get secret db-creds -o yamlHiển thị Secret (mã hóa base64)
Namespaces
Lệnh Namespace
kubectl get nsLiệt kê namespaces
kubectl create ns stagingTạo namespace
kubectl delete ns stagingXóa namespace và tất cả tài nguyên
kubectl get pods -n stagingLiệt kê pods trong namespace
kubectl get pods -ALiệt kê pods trên tất cả namespaces
Đặt Namespace Mặc Định
kubectl config set-context --current \ --namespace=staging
Volumes
PersistentVolumeClaim
apiVersion: v1 kind: PersistentVolumeClaim metadata: name: data-pvc spec: accessModes: [ReadWriteOnce] resources: requests: { storage: 10Gi }
Mount Trong Pod
volumes: - name: data persistentVolumeClaim: claimName: data-pvc containers: - volumeMounts: - name: data mountPath: /app/data
Loại Volume
emptyDirThư mục tạm, bị xóa cùng pod
hostPathMount đường dẫn filesystem của host
persistentVolumeClaimStorage bền vững (PVC)
configMapMount ConfigMap dưới dạng file
secretMount Secret dưới dạng file
Ingress
Ingress YAML
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: web-ingress spec: rules: - host: app.example.com http: paths: - path: / pathType: Prefix backend: service: name: web-svc port: { number: 80 }
Ghi Chú Ingress
Ingress ControllerBắt buộc (nginx-ingress, traefik, v.v.)
pathType: PrefixKhớp tiền tố URL
pathType: ExactKhớp chính xác đường dẫn URL
TLSThêm phần tls: với tên secret
Debugging
Lệnh Chẩn Đoán
kubectl logs <pod>stdout/stderr của container
kubectl logs <pod> -c <ctr>Log của container cụ thể
kubectl logs <pod> --previousLog từ container bị crash
kubectl describe pod <pod>Events, điều kiện, trạng thái
kubectl exec -it <pod> -- shShell vào container
kubectl port-forward <pod> 8080:80Chuyển tiếp port cục bộ đến pod
kubectl top podsSử dụng CPU/memory (metrics-server)
kubectl get events --sort-by=.lastTimestampDòng thời gian sự kiện cluster
Debug Pod
kubectl run debug --rm -it --image=busybox -- sh # or attach ephemeral container kubectl debug -it --image=busybox
Mẫu Phổ Biến
Labels & Selectors
kubectl get pods -l app=web kubectl get pods -l 'env in (prod,staging)' kubectl label pod myapp env=prod
Giới Hạn Tài Nguyên
resources: requests: { cpu: 100m, memory: 128Mi } limits: { cpu: 500m, memory: 256Mi }
Liveness & Readiness
livenessProbe: httpGet: { path: /healthz, port: 8080 } initialDelaySeconds: 5 periodSeconds: 10 readinessProbe: httpGet: { path: /ready, port: 8080 }
Công Thức Nhanh
Dry runkubectl apply -f file.yaml --dry-run=client
Generate YAMLkubectl create deploy web --image=nginx --dry-run=client -o yaml
Watchkubectl get pods -w
Copy fileskubectl cp file.txt pod:/tmp/
Restart deploykubectl rollout restart deploy/web