🎯 前言
在上一篇文章中,我們了解了 Kubernetes 的基礎概念與架構。本文將深入探討核心資源對象的實務操作,透過大量範例與表格說明,幫助你全面掌握 K8s 的日常操作。
本文重點:
- kubectl 指令完全指南
- Pod 深度解析與操作
- Workload 資源管理
- Service 與網路配置
- Ingress 路由管理
- 儲存資源操作
- 配置管理實戰
🔧 kubectl 指令完全指南
kubectl 指令結構
1kubectl [command] [TYPE] [NAME] [flags]
範例:
1kubectl get pods nginx-pod -o yaml
2# ↑ ↑ ↑ ↑
3# 指令 類型 名稱 選項
基本指令分類
graph TB
A[kubectl 指令] --> B[基礎操作]
A --> C[部署管理]
A --> D[除錯診斷]
A --> E[叢集管理]
A --> F[設定管理]
B --> B1[get, describe<br/>logs, exec]
C --> C1[create, apply<br/>delete, scale]
D --> D1[logs, exec<br/>port-forward, top]
E --> E1[cluster-info<br/>api-resources<br/>api-versions]
F --> F1[config<br/>auth]
style A fill:#326ce5
style B fill:#4ecdc4
style C fill:#feca57
style D fill:#ff6b6b
style E fill:#a8e6cf
style F fill:#ffb3ba
kubectl 常用指令速查表
基礎操作指令
指令 | 用途 | 範例 |
---|---|---|
get | 列出資源 | kubectl get pods |
describe | 查看詳細資訊 | kubectl describe pod nginx |
create | 創建資源 | kubectl create deployment nginx --image=nginx |
apply | 應用配置 | kubectl apply -f deployment.yaml |
delete | 刪除資源 | kubectl delete pod nginx |
edit | 編輯資源 | kubectl edit deployment nginx |
exec | 在容器中執行指令 | kubectl exec -it nginx -- bash |
logs | 查看日誌 | kubectl logs nginx |
port-forward | 埠轉發 | kubectl port-forward pod/nginx 8080:80 |
進階操作指令
指令 | 用途 | 範例 |
---|---|---|
scale | 擴展副本數 | kubectl scale deployment nginx --replicas=5 |
rollout | 更新管理 | kubectl rollout status deployment/nginx |
label | 管理標籤 | kubectl label pod nginx env=prod |
annotate | 管理註解 | kubectl annotate pod nginx description="web server" |
expose | 暴露服務 | kubectl expose deployment nginx --port=80 |
top | 資源使用情況 | kubectl top nodes |
cp | 複製檔案 | kubectl cp nginx:/tmp/file ./file |
attach | 附加到容器 | kubectl attach nginx -it |
kubectl 輸出格式
1# 預設輸出
2kubectl get pods
3
4# 寬輸出(更多資訊)
5kubectl get pods -o wide
6
7# YAML 格式
8kubectl get pod nginx -o yaml
9
10# JSON 格式
11kubectl get pod nginx -o json
12
13# 自訂欄位
14kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase
15
16# JSONPath 查詢
17kubectl get pods -o jsonpath='{.items[*].metadata.name}'
18
19# 使用模板
20kubectl get pods -o go-template='{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'
21
22# 只顯示名稱
23kubectl get pods -o name
kubectl 實用技巧
1# 查看所有命名空間的資源
2kubectl get pods --all-namespaces
3kubectl get all -A # 簡寫
4
5# 監視資源變化
6kubectl get pods --watch
7kubectl get pods -w # 簡寫
8
9# 排序輸出
10kubectl get pods --sort-by=.metadata.creationTimestamp
11kubectl get pods --sort-by=.status.startTime
12
13# 過濾標籤
14kubectl get pods -l app=nginx
15kubectl get pods -l 'env in (prod,staging)'
16kubectl get pods -l app=nginx,tier=frontend
17
18# 欄位選擇器
19kubectl get pods --field-selector status.phase=Running
20kubectl get pods --field-selector metadata.namespace=default
21
22# 顯示標籤
23kubectl get pods --show-labels
24
25# 乾跑(不實際執行)
26kubectl apply -f deployment.yaml --dry-run=client
27kubectl apply -f deployment.yaml --dry-run=server
28
29# 輸出到檔案
30kubectl get deployment nginx -o yaml > nginx-deployment.yaml
31
32# 查看 API 資源
33kubectl api-resources
34kubectl api-versions
35
36# 解釋資源欄位
37kubectl explain pod
38kubectl explain pod.spec
39kubectl explain pod.spec.containers
📦 Pod 深度解析
Pod 生命週期
stateDiagram-v2
[*] --> Pending: 創建 Pod
Pending --> Running: 容器啟動成功
Pending --> Failed: 啟動失敗
Running --> Succeeded: 正常結束
Running --> Failed: 異常結束
Running --> Unknown: 節點失聯
Succeeded --> [*]
Failed --> [*]
Unknown --> Running: 節點恢復
Unknown --> Failed: 超時失敗
Pod 階段(Phase)說明
階段 | 說明 | 何時出現 |
---|---|---|
Pending | 等待中 | Pod 已創建但容器未啟動 |
Running | 運行中 | 至少一個容器正在運行 |
Succeeded | 成功 | 所有容器成功終止(Job) |
Failed | 失敗 | 容器非零退出或被系統終止 |
Unknown | 未知 | 無法獲取 Pod 狀態 |
Pod 完整配置範例
1apiVersion: v1
2kind: Pod
3metadata:
4 name: nginx-pod
5 namespace: default
6 labels:
7 app: nginx
8 tier: frontend
9 environment: production
10 annotations:
11 description: "Nginx web server"
12 version: "1.24"
13spec:
14 # 容器定義
15 containers:
16 - name: nginx
17 image: nginx:1.24
18 imagePullPolicy: IfNotPresent # Always, Never, IfNotPresent
19
20 # 埠配置
21 ports:
22 - name: http
23 containerPort: 80
24 protocol: TCP
25
26 # 環境變數
27 env:
28 - name: NGINX_PORT
29 value: "80"
30 - name: NGINX_HOST
31 valueFrom:
32 configMapKeyRef:
33 name: nginx-config
34 key: host
35
36 # 資源限制
37 resources:
38 requests:
39 memory: "128Mi"
40 cpu: "250m"
41 limits:
42 memory: "256Mi"
43 cpu: "500m"
44
45 # Volume 掛載
46 volumeMounts:
47 - name: html
48 mountPath: /usr/share/nginx/html
49 - name: config
50 mountPath: /etc/nginx/nginx.conf
51 subPath: nginx.conf
52
53 # 健康檢查
54 livenessProbe:
55 httpGet:
56 path: /
57 port: 80
58 initialDelaySeconds: 30
59 periodSeconds: 10
60 timeoutSeconds: 5
61 failureThreshold: 3
62
63 readinessProbe:
64 httpGet:
65 path: /
66 port: 80
67 initialDelaySeconds: 10
68 periodSeconds: 5
69
70 # 啟動探測
71 startupProbe:
72 httpGet:
73 path: /
74 port: 80
75 initialDelaySeconds: 0
76 periodSeconds: 10
77 failureThreshold: 30
78
79 # 生命週期鉤子
80 lifecycle:
81 postStart:
82 exec:
83 command: ["/bin/sh", "-c", "echo Hello from the postStart handler > /usr/share/message"]
84 preStop:
85 exec:
86 command: ["/bin/sh", "-c", "nginx -s quit; while killall -0 nginx; do sleep 1; done"]
87
88 # Init 容器
89 initContainers:
90 - name: init-html
91 image: busybox:1.35
92 command: ['sh', '-c', 'echo "<h1>Initialized</h1>" > /work-dir/index.html']
93 volumeMounts:
94 - name: html
95 mountPath: /work-dir
96
97 # Volume 定義
98 volumes:
99 - name: html
100 emptyDir: {}
101 - name: config
102 configMap:
103 name: nginx-config
104
105 # DNS 配置
106 dnsPolicy: ClusterFirst
107 dnsConfig:
108 nameservers:
109 - 8.8.8.8
110 searches:
111 - default.svc.cluster.local
112 - svc.cluster.local
113
114 # 主機網路
115 hostNetwork: false
116 hostPID: false
117 hostIPC: false
118
119 # 重啟策略
120 restartPolicy: Always # Always, OnFailure, Never
121
122 # 節點選擇
123 nodeSelector:
124 disktype: ssd
125
126 # 親和性
127 affinity:
128 nodeAffinity:
129 requiredDuringSchedulingIgnoredDuringExecution:
130 nodeSelectorTerms:
131 - matchExpressions:
132 - key: kubernetes.io/hostname
133 operator: In
134 values:
135 - node-1
136 - node-2
137
138 # 容忍
139 tolerations:
140 - key: "key1"
141 operator: "Equal"
142 value: "value1"
143 effect: "NoSchedule"
144
145 # 安全上下文
146 securityContext:
147 runAsUser: 1000
148 runAsGroup: 3000
149 fsGroup: 2000
150
151 # 服務帳戶
152 serviceAccountName: default
153
154 # 優先級
155 priorityClassName: high-priority
156
157 # 終止寬限期
158 terminationGracePeriodSeconds: 30
健康檢查對照表
探測類型 | 用途 | 失敗影響 |
---|---|---|
livenessProbe | 檢查容器是否存活 | 重啟容器 |
readinessProbe | 檢查容器是否就緒 | 從 Service 移除 |
startupProbe | 檢查容器是否啟動 | 重啟容器 |
探測方法:
方法 | 說明 | 適用場景 |
---|---|---|
httpGet | HTTP GET 請求 | Web 應用 |
tcpSocket | TCP 連接 | 數據庫、非 HTTP 服務 |
exec | 執行命令 | 自訂檢查邏輯 |
grpc | gRPC 健康檢查 | gRPC 服務 |
Pod 操作指令
1# 創建 Pod
2kubectl run nginx --image=nginx:1.24
3kubectl apply -f pod.yaml
4
5# 查看 Pod
6kubectl get pods
7kubectl get pods -o wide
8kubectl get pods --show-labels
9kubectl get pods -l app=nginx
10
11# 查看詳細資訊
12kubectl describe pod nginx
13
14# 查看日誌
15kubectl logs nginx
16kubectl logs nginx -c container-name # 多容器
17kubectl logs nginx --previous # 查看之前容器的日誌
18kubectl logs nginx --tail=100 # 最後 100 行
19kubectl logs nginx -f # 實時跟蹤
20
21# 進入容器
22kubectl exec -it nginx -- bash
23kubectl exec nginx -- ls /usr/share/nginx/html
24
25# 埠轉發
26kubectl port-forward pod/nginx 8080:80
27curl http://localhost:8080
28
29# 複製檔案
30kubectl cp nginx:/etc/nginx/nginx.conf ./nginx.conf
31kubectl cp ./index.html nginx:/usr/share/nginx/html/
32
33# 查看資源使用
34kubectl top pod nginx
35
36# 刪除 Pod
37kubectl delete pod nginx
38kubectl delete pod --all
39kubectl delete pod nginx --force --grace-period=0 # 強制刪除
🚀 Workload 資源管理
Deployment - 無狀態應用
Deployment 完整配置:
1apiVersion: apps/v1
2kind: Deployment
3metadata:
4 name: nginx-deployment
5 namespace: default
6 labels:
7 app: nginx
8 annotations:
9 kubernetes.io/change-cause: "Update to version 1.24"
10spec:
11 # 副本數
12 replicas: 3
13
14 # 選擇器
15 selector:
16 matchLabels:
17 app: nginx
18
19 # 更新策略
20 strategy:
21 type: RollingUpdate # RollingUpdate 或 Recreate
22 rollingUpdate:
23 maxSurge: 1 # 最多超出的 Pod 數
24 maxUnavailable: 1 # 最多不可用的 Pod 數
25
26 # 最小就緒時間
27 minReadySeconds: 10
28
29 # 修訂版本歷史限制
30 revisionHistoryLimit: 10
31
32 # Pod 模板
33 template:
34 metadata:
35 labels:
36 app: nginx
37 version: "1.24"
38 spec:
39 containers:
40 - name: nginx
41 image: nginx:1.24
42 ports:
43 - containerPort: 80
44 resources:
45 requests:
46 memory: "64Mi"
47 cpu: "250m"
48 limits:
49 memory: "128Mi"
50 cpu: "500m"
51 livenessProbe:
52 httpGet:
53 path: /
54 port: 80
55 initialDelaySeconds: 30
56 periodSeconds: 10
57 readinessProbe:
58 httpGet:
59 path: /
60 port: 80
61 initialDelaySeconds: 5
62 periodSeconds: 5
Deployment 操作指令
1# 創建 Deployment
2kubectl create deployment nginx --image=nginx:1.24
3kubectl apply -f deployment.yaml
4
5# 查看 Deployment
6kubectl get deployments
7kubectl get deploy # 簡寫
8kubectl describe deployment nginx
9
10# 擴展副本
11kubectl scale deployment nginx --replicas=5
12kubectl autoscale deployment nginx --min=2 --max=10 --cpu-percent=80
13
14# 更新映像
15kubectl set image deployment/nginx nginx=nginx:1.25
16kubectl set image deployment/nginx nginx=nginx:1.25 --record
17
18# 編輯 Deployment
19kubectl edit deployment nginx
20
21# 查看更新狀態
22kubectl rollout status deployment/nginx
23kubectl rollout history deployment/nginx
24kubectl rollout history deployment/nginx --revision=2
25
26# 暫停/恢復更新
27kubectl rollout pause deployment/nginx
28kubectl rollout resume deployment/nginx
29
30# 回滾
31kubectl rollout undo deployment/nginx
32kubectl rollout undo deployment/nginx --to-revision=2
33
34# 重啟 Deployment(滾動重啟所有 Pod)
35kubectl rollout restart deployment/nginx
36
37# 刪除 Deployment
38kubectl delete deployment nginx
更新策略對照表
策略類型 | 說明 | 適用場景 | 停機時間 |
---|---|---|---|
RollingUpdate | 逐步替換舊 Pod | 無狀態應用 | 無 |
Recreate | 先刪除所有舊 Pod 再創建新 Pod | 不支援多版本共存 | 有 |
StatefulSet - 有狀態應用
1apiVersion: apps/v1
2kind: StatefulSet
3metadata:
4 name: mysql
5spec:
6 serviceName: mysql
7 replicas: 3
8 selector:
9 matchLabels:
10 app: mysql
11 template:
12 metadata:
13 labels:
14 app: mysql
15 spec:
16 containers:
17 - name: mysql
18 image: mysql:8.0
19 ports:
20 - containerPort: 3306
21 name: mysql
22 env:
23 - name: MYSQL_ROOT_PASSWORD
24 valueFrom:
25 secretKeyRef:
26 name: mysql-secret
27 key: password
28 volumeMounts:
29 - name: data
30 mountPath: /var/lib/mysql
31 volumeClaimTemplates:
32 - metadata:
33 name: data
34 spec:
35 accessModes: ["ReadWriteOnce"]
36 storageClassName: standard
37 resources:
38 requests:
39 storage: 10Gi
StatefulSet 特性:
特性 | Deployment | StatefulSet |
---|---|---|
Pod 名稱 | 隨機 | 固定(有序) |
網路標識 | 不穩定 | 穩定 DNS |
儲存 | 共享 | 專屬 PVC |
啟動順序 | 並行 | 有序 |
更新順序 | 隨機 | 有序 |
適用場景 | 無狀態 | 資料庫、叢集 |
DaemonSet - 每節點一個 Pod
1apiVersion: apps/v1
2kind: DaemonSet
3metadata:
4 name: fluentd
5 namespace: kube-system
6spec:
7 selector:
8 matchLabels:
9 app: fluentd
10 template:
11 metadata:
12 labels:
13 app: fluentd
14 spec:
15 tolerations:
16 - key: node-role.kubernetes.io/master
17 effect: NoSchedule
18 containers:
19 - name: fluentd
20 image: fluentd:v1.14
21 resources:
22 limits:
23 memory: 200Mi
24 requests:
25 cpu: 100m
26 memory: 200Mi
27 volumeMounts:
28 - name: varlog
29 mountPath: /var/log
30 volumes:
31 - name: varlog
32 hostPath:
33 path: /var/log
DaemonSet 使用場景:
- 日誌收集(Fluentd、Filebeat)
- 監控代理(Node Exporter、Datadog)
- 儲存守護進程(Ceph、GlusterFS)
- 網路插件(Calico、Flannel)
Job & CronJob - 任務管理
Job 一次性任務:
1apiVersion: batch/v1
2kind: Job
3metadata:
4 name: pi-calculation
5spec:
6 # 完成數
7 completions: 5
8 # 並行數
9 parallelism: 2
10 # 重試次數
11 backoffLimit: 4
12 # 超時時間
13 activeDeadlineSeconds: 100
14 template:
15 spec:
16 containers:
17 - name: pi
18 image: perl:5.34
19 command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"]
20 restartPolicy: Never
CronJob 定時任務:
1apiVersion: batch/v1
2kind: CronJob
3metadata:
4 name: backup-job
5spec:
6 # Cron 表達式
7 schedule: "0 2 * * *" # 每天凌晨 2 點
8 # 時區
9 timeZone: "Asia/Taipei"
10 # 並發策略
11 concurrencyPolicy: Forbid # Allow, Forbid, Replace
12 # 保留成功任務數
13 successfulJobsHistoryLimit: 3
14 # 保留失敗任務數
15 failedJobsHistoryLimit: 1
16 # 啟動截止時間
17 startingDeadlineSeconds: 100
18 jobTemplate:
19 spec:
20 template:
21 spec:
22 containers:
23 - name: backup
24 image: backup-tool:latest
25 command: ["/bin/sh", "-c", "backup.sh"]
26 restartPolicy: OnFailure
🌐 Service 與網路配置
Service 類型詳解
graph TB
subgraph "ClusterIP"
C1[內部 IP]
C2[叢集內存取]
C3[預設類型]
end
subgraph "NodePort"
N1[節點 IP:Port]
N2[外部可存取]
N3[埠範圍 30000-32767]
end
subgraph "LoadBalancer"
L1[雲端 LB]
L2[自動分配外部 IP]
L3[依賴雲端供應商]
end
subgraph "ExternalName"
E1[DNS CNAME]
E2[映射外部服務]
E3[無代理]
end
style C1 fill:#326ce5
style N1 fill:#4ecdc4
style L1 fill:#feca57
style E1 fill:#ff6b6b
Service 完整配置範例
1apiVersion: v1
2kind: Service
3metadata:
4 name: nginx-service
5 namespace: default
6 labels:
7 app: nginx
8 annotations:
9 service.beta.kubernetes.io/aws-load-balancer-type: "nlb"
10spec:
11 # Service 類型
12 type: LoadBalancer # ClusterIP, NodePort, LoadBalancer, ExternalName
13
14 # 選擇器
15 selector:
16 app: nginx
17
18 # 埠配置
19 ports:
20 - name: http
21 protocol: TCP
22 port: 80 # Service 埠
23 targetPort: 80 # Pod 埠
24 nodePort: 30080 # NodePort(type=NodePort 時)
25 - name: https
26 protocol: TCP
27 port: 443
28 targetPort: 443
29
30 # ClusterIP 配置
31 clusterIP: 10.0.0.100 # 可指定或設為 None(Headless Service)
32
33 # 會話親和性
34 sessionAffinity: ClientIP
35 sessionAffinityConfig:
36 clientIP:
37 timeoutSeconds: 10800
38
39 # 外部流量策略
40 externalTrafficPolicy: Local # Cluster 或 Local
41
42 # 健康檢查節點埠
43 healthCheckNodePort: 30000
44
45 # 負載均衡器設定
46 loadBalancerIP: 203.0.113.10
47 loadBalancerSourceRanges:
48 - 203.0.113.0/24
49
50 # 外部 IP
51 externalIPs:
52 - 203.0.113.20
Service 類型對照表
類型 | ClusterIP | NodePort | LoadBalancer | ExternalName |
---|---|---|---|---|
存取方式 | 內部 IP | 節點 IP:Port | 外部 LB IP | DNS CNAME |
外部存取 | ❌ | ✅ | ✅ | ✅ |
埠範圍 | 任意 | 30000-32767 | 任意 | N/A |
雲端依賴 | ❌ | ❌ | ✅ | ❌ |
適用場景 | 內部服務 | 開發測試 | 生產環境 | 外部整合 |
負載均衡 | ✅ | ✅ | ✅ | ❌ |
Headless Service
1apiVersion: v1
2kind: Service
3metadata:
4 name: mysql-headless
5spec:
6 clusterIP: None # Headless Service
7 selector:
8 app: mysql
9 ports:
10 - port: 3306
11 targetPort: 3306
用途:
- StatefulSet 服務發現
- 自訂負載均衡
- 直接獲取 Pod IP
Service 操作指令
1# 創建 Service
2kubectl expose deployment nginx --port=80 --type=NodePort
3kubectl apply -f service.yaml
4
5# 查看 Service
6kubectl get services
7kubectl get svc # 簡寫
8kubectl get svc -o wide
9kubectl describe svc nginx
10
11# 查看 Endpoints
12kubectl get endpoints nginx
13kubectl get ep nginx # 簡寫
14
15# 測試 Service(從 Pod 內部)
16kubectl run test --rm -it --image=busybox -- sh
17wget -O- http://nginx-service
18
19# 查看 Service 對應的 Pod
20kubectl get pods -l app=nginx
21
22# 刪除 Service
23kubectl delete svc nginx
🔀 Ingress 路由管理
Ingress 架構
graph LR
CLIENT[客戶端] --> INGRESS[Ingress Controller<br/>Nginx/Traefik]
INGRESS --> SVC1[Service: web]
INGRESS --> SVC2[Service: api]
INGRESS --> SVC3[Service: admin]
SVC1 --> POD1[Pod: web]
SVC2 --> POD2[Pod: api]
SVC3 --> POD3[Pod: admin]
INGRESS -.->|app.example.com| SVC1
INGRESS -.->|api.example.com| SVC2
INGRESS -.->|admin.example.com| SVC3
style INGRESS fill:#326ce5
style SVC1 fill:#4ecdc4
style SVC2 fill:#4ecdc4
style SVC3 fill:#4ecdc4
Ingress 完整配置
1apiVersion: networking.k8s.io/v1
2kind: Ingress
3metadata:
4 name: app-ingress
5 namespace: default
6 annotations:
7 # Nginx Ingress 註解
8 nginx.ingress.kubernetes.io/rewrite-target: /
9 nginx.ingress.kubernetes.io/ssl-redirect: "true"
10 nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
11 nginx.ingress.kubernetes.io/proxy-body-size: "10m"
12 nginx.ingress.kubernetes.io/proxy-connect-timeout: "600"
13 nginx.ingress.kubernetes.io/proxy-send-timeout: "600"
14 nginx.ingress.kubernetes.io/proxy-read-timeout: "600"
15 nginx.ingress.kubernetes.io/rate-limit: "100"
16 nginx.ingress.kubernetes.io/limit-rps: "10"
17
18 # CORS 設定
19 nginx.ingress.kubernetes.io/enable-cors: "true"
20 nginx.ingress.kubernetes.io/cors-allow-origin: "*"
21
22 # 認證
23 nginx.ingress.kubernetes.io/auth-type: basic
24 nginx.ingress.kubernetes.io/auth-secret: basic-auth
25 nginx.ingress.kubernetes.io/auth-realm: 'Authentication Required'
26
27 # TLS 設定
28 cert-manager.io/cluster-issuer: "letsencrypt-prod"
29spec:
30 # Ingress Class
31 ingressClassName: nginx
32
33 # TLS 配置
34 tls:
35 - hosts:
36 - app.example.com
37 - api.example.com
38 secretName: tls-secret
39
40 # 路由規則
41 rules:
42 # 主應用
43 - host: app.example.com
44 http:
45 paths:
46 - path: /
47 pathType: Prefix
48 backend:
49 service:
50 name: web-service
51 port:
52 number: 80
53
54 # API 服務
55 - host: api.example.com
56 http:
57 paths:
58 - path: /v1
59 pathType: Prefix
60 backend:
61 service:
62 name: api-service
63 port:
64 number: 8080
65 - path: /v2
66 pathType: Prefix
67 backend:
68 service:
69 name: api-v2-service
70 port:
71 number: 8080
72
73 # 管理後台
74 - host: admin.example.com
75 http:
76 paths:
77 - path: /
78 pathType: Prefix
79 backend:
80 service:
81 name: admin-service
82 port:
83 number: 3000
84
85 # 預設後端
86 defaultBackend:
87 service:
88 name: default-backend
89 port:
90 number: 80
PathType 對照表
PathType | 說明 | 範例 | 匹配規則 |
---|---|---|---|
Prefix | 前綴匹配 | /api | /api , /api/v1 , /api/users |
Exact | 精確匹配 | /api | 只匹配 /api |
ImplementationSpecific | 由 Ingress Controller 決定 | /api | 依 Controller 而定 |
安裝 Ingress Controller
1# Nginx Ingress Controller
2kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.8.1/deploy/static/provider/cloud/deploy.yaml
3
4# 驗證安裝
5kubectl get pods -n ingress-nginx
6kubectl get svc -n ingress-nginx
7
8# Minikube 啟用 Ingress
9minikube addons enable ingress
Ingress 操作指令
1# 創建 Ingress
2kubectl apply -f ingress.yaml
3
4# 查看 Ingress
5kubectl get ingress
6kubectl get ing # 簡寫
7kubectl describe ingress app-ingress
8
9# 查看 Ingress Class
10kubectl get ingressclass
11
12# 測試 Ingress(需要配置 DNS 或 hosts)
13curl -H "Host: app.example.com" http://<INGRESS_IP>
14
15# 編輯 Ingress
16kubectl edit ingress app-ingress
17
18# 刪除 Ingress
19kubectl delete ingress app-ingress
💾 儲存資源管理
儲存資源層級
graph TB
SC[StorageClass<br/>儲存類別] --> PV[PersistentVolume<br/>持久卷]
PV --> PVC[PersistentVolumeClaim<br/>持久卷聲明]
PVC --> POD[Pod]
SC -.->|動態佈建| PV
PVC -.->|綁定| PV
POD -.->|使用| PVC
style SC fill:#326ce5
style PV fill:#4ecdc4
style PVC fill:#feca57
style POD fill:#ff6b6b
StorageClass 配置
1apiVersion: storage.k8s.io/v1
2kind: StorageClass
3metadata:
4 name: fast-ssd
5provisioner: kubernetes.io/aws-ebs
6parameters:
7 type: gp3
8 iopsPerGB: "10"
9 fsType: ext4
10 encrypted: "true"
11volumeBindingMode: WaitForFirstConsumer
12allowVolumeExpansion: true
13reclaimPolicy: Delete
ReclaimPolicy 對照表:
策略 | 說明 | 資料保留 |
---|---|---|
Delete | 刪除 PVC 時刪除 PV | ❌ |
Retain | 保留 PV | ✅ |
Recycle | 清理並重用(已棄用) | ❌ |
PersistentVolume 配置
1apiVersion: v1
2kind: PersistentVolume
3metadata:
4 name: pv-nfs
5spec:
6 capacity:
7 storage: 10Gi
8 volumeMode: Filesystem
9 accessModes:
10 - ReadWriteMany
11 persistentVolumeReclaimPolicy: Retain
12 storageClassName: nfs
13 mountOptions:
14 - hard
15 - nfsvers=4.1
16 nfs:
17 path: /data
18 server: nfs-server.example.com
AccessModes 對照表:
模式 | 簡寫 | 說明 | 適用場景 |
---|---|---|---|
ReadWriteOnce | RWO | 單節點讀寫 | 資料庫 |
ReadOnlyMany | ROX | 多節點唯讀 | 靜態資源 |
ReadWriteMany | RWX | 多節點讀寫 | 共享檔案系統 |
ReadWriteOncePod | RWOP | 單 Pod 讀寫 | 嚴格隔離 |
PersistentVolumeClaim 配置
1apiVersion: v1
2kind: PersistentVolumeClaim
3metadata:
4 name: mysql-pvc
5spec:
6 accessModes:
7 - ReadWriteOnce
8 volumeMode: Filesystem
9 resources:
10 requests:
11 storage: 10Gi
12 storageClassName: fast-ssd
13 selector:
14 matchLabels:
15 environment: production
儲存操作指令
1# StorageClass
2kubectl get storageclass
3kubectl get sc # 簡寫
4kubectl describe sc fast-ssd
5
6# PersistentVolume
7kubectl get persistentvolumes
8kubectl get pv # 簡寫
9kubectl describe pv pv-nfs
10
11# PersistentVolumeClaim
12kubectl get persistentvolumeclaims
13kubectl get pvc # 簡寫
14kubectl describe pvc mysql-pvc
15
16# 查看 PVC 綁定狀態
17kubectl get pvc -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,VOLUME:.spec.volumeName
18
19# 擴展 PVC(需要 StorageClass 支援)
20kubectl patch pvc mysql-pvc -p '{"spec":{"resources":{"requests":{"storage":"20Gi"}}}}'
21
22# 刪除 PVC
23kubectl delete pvc mysql-pvc
⚙️ ConfigMap & Secret 實戰
ConfigMap 完整範例
1apiVersion: v1
2kind: ConfigMap
3metadata:
4 name: app-config
5 namespace: default
6data:
7 # 簡單鍵值對
8 database_host: "mysql.default.svc.cluster.local"
9 database_port: "3306"
10 log_level: "info"
11
12 # 配置檔案
13 app.properties: |
14 server.port=8080
15 server.host=0.0.0.0
16 logging.level=INFO
17
18 nginx.conf: |
19 server {
20 listen 80;
21 server_name localhost;
22 location / {
23 root /usr/share/nginx/html;
24 index index.html;
25 }
26 }
Secret 完整範例
1apiVersion: v1
2kind: Secret
3metadata:
4 name: app-secret
5 namespace: default
6type: Opaque
7data:
8 # Base64 編碼
9 database_password: cGFzc3dvcmQxMjM=
10 api_key: YWJjZGVmMTIzNDU2
11stringData:
12 # 明文(自動編碼)
13 admin_password: "admin123"
14 smtp_password: "smtp_pass"
Secret 類型對照表:
類型 | 用途 | 範例 |
---|---|---|
Opaque | 一般密鑰 | 密碼、Token |
kubernetes.io/service-account-token | ServiceAccount Token | 自動創建 |
kubernetes.io/dockercfg | Docker 配置(舊) | 映像拉取 |
kubernetes.io/dockerconfigjson | Docker 配置 | 映像拉取 |
kubernetes.io/basic-auth | 基本認證 | 使用者名/密碼 |
kubernetes.io/ssh-auth | SSH 認證 | SSH 私鑰 |
kubernetes.io/tls | TLS 證書 | 證書和私鑰 |
在 Pod 中使用 ConfigMap 和 Secret
1apiVersion: v1
2kind: Pod
3metadata:
4 name: app-pod
5spec:
6 containers:
7 - name: app
8 image: myapp:latest
9
10 # 方式 1: 環境變數
11 env:
12 # 從 ConfigMap
13 - name: DATABASE_HOST
14 valueFrom:
15 configMapKeyRef:
16 name: app-config
17 key: database_host
18
19 # 從 Secret
20 - name: DATABASE_PASSWORD
21 valueFrom:
22 secretKeyRef:
23 name: app-secret
24 key: database_password
25
26 # 方式 2: 所有鍵作為環境變數
27 envFrom:
28 - configMapRef:
29 name: app-config
30 - secretRef:
31 name: app-secret
32
33 # 方式 3: Volume 掛載
34 volumeMounts:
35 - name: config-volume
36 mountPath: /etc/config
37 - name: secret-volume
38 mountPath: /etc/secret
39 readOnly: true
40
41 volumes:
42 - name: config-volume
43 configMap:
44 name: app-config
45 items:
46 - key: nginx.conf
47 path: nginx.conf
48
49 - name: secret-volume
50 secret:
51 secretName: app-secret
52 defaultMode: 0400
ConfigMap & Secret 操作指令
1# 創建 ConfigMap
2kubectl create configmap app-config --from-literal=key1=value1 --from-literal=key2=value2
3kubectl create configmap app-config --from-file=config.properties
4kubectl create configmap app-config --from-file=configs/
5kubectl apply -f configmap.yaml
6
7# 創建 Secret
8kubectl create secret generic app-secret --from-literal=password=secret123
9kubectl create secret generic app-secret --from-file=./username.txt --from-file=./password.txt
10kubectl create secret docker-registry regcred \
11 --docker-server=<registry-server> \
12 --docker-username=<username> \
13 --docker-password=<password> \
14 --docker-email=<email>
15
16# 創建 TLS Secret
17kubectl create secret tls tls-secret \
18 --cert=path/to/cert.crt \
19 --key=path/to/cert.key
20
21# 查看 ConfigMap
22kubectl get configmap
23kubectl get cm # 簡寫
24kubectl describe cm app-config
25kubectl get cm app-config -o yaml
26
27# 查看 Secret
28kubectl get secret
29kubectl describe secret app-secret
30kubectl get secret app-secret -o yaml
31
32# 解碼 Secret
33kubectl get secret app-secret -o jsonpath='{.data.password}' | base64 --decode
34
35# 編輯
36kubectl edit cm app-config
37kubectl edit secret app-secret
38
39# 刪除
40kubectl delete cm app-config
41kubectl delete secret app-secret
🎯 實用技巧與最佳實踐
kubectl 進階技巧
1# 快速創建資源(乾跑輸出 YAML)
2kubectl run nginx --image=nginx --dry-run=client -o yaml > pod.yaml
3kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > deployment.yaml
4kubectl create service clusterip nginx --tcp=80:80 --dry-run=client -o yaml > service.yaml
5
6# 一次性指令 Pod
7kubectl run test --rm -it --image=busybox -- sh
8kubectl run curl --rm -it --image=curlimages/curl -- sh
9
10# 快速除錯
11kubectl debug node/node-1 -it --image=ubuntu
12kubectl debug pod/nginx -it --image=busybox --target=nginx
13
14# 查看資源消耗
15kubectl top nodes
16kubectl top pods
17kubectl top pods --all-namespaces --sort-by=memory
18
19# 查看 API 資源
20kubectl api-resources --namespaced=true
21kubectl api-resources --namespaced=false
22kubectl api-resources -o wide
23
24# 查看資源定義
25kubectl explain pod
26kubectl explain pod.spec.containers
27kubectl explain deployment.spec.strategy
28
29# 查看事件
30kubectl get events --sort-by=.metadata.creationTimestamp
31kubectl get events --field-selector type=Warning
32
33# 強制刪除
34kubectl delete pod nginx --force --grace-period=0
35
36# 查看資源關係
37kubectl get all -l app=nginx
38kubectl get all,cm,secret,pvc -l app=nginx
YAML 最佳實踐
1. 使用多文件分隔:
1apiVersion: apps/v1
2kind: Deployment
3metadata:
4 name: nginx
5spec:
6 replicas: 3
7 # ... deployment spec
8
9---
10apiVersion: v1
11kind: Service
12metadata:
13 name: nginx
14spec:
15 # ... service spec
2. 使用標籤規範:
1metadata:
2 labels:
3 app.kubernetes.io/name: nginx
4 app.kubernetes.io/instance: nginx-prod
5 app.kubernetes.io/version: "1.24"
6 app.kubernetes.io/component: webserver
7 app.kubernetes.io/part-of: myapp
8 app.kubernetes.io/managed-by: kubectl
3. 資源限制:
1resources:
2 requests:
3 memory: "64Mi"
4 cpu: "250m"
5 limits:
6 memory: "128Mi"
7 cpu: "500m"
常見問題排查
1# Pod 無法啟動
2kubectl describe pod <pod-name>
3kubectl logs <pod-name>
4kubectl logs <pod-name> --previous
5kubectl get events --field-selector involvedObject.name=<pod-name>
6
7# Service 無法存取
8kubectl get endpoints <service-name>
9kubectl describe svc <service-name>
10kubectl run test --rm -it --image=busybox -- wget -O- http://<service-name>
11
12# 映像拉取失敗
13kubectl describe pod <pod-name> | grep -A 5 "Events:"
14kubectl get secret <image-pull-secret> -o yaml
15
16# 資源不足
17kubectl describe nodes
18kubectl top nodes
19kubectl get pods --all-namespaces -o wide --field-selector spec.nodeName=<node-name>
20
21# 檢查權限
22kubectl auth can-i create deployments
23kubectl auth can-i delete pods --namespace=default
24kubectl auth can-i '*' '*' --all-namespaces
📊 總結
本文深入介紹了 Kubernetes 核心資源的實務操作:
核心內容回顧
kubectl 指令體系
- 基礎與進階指令
- 輸出格式與過濾
- 實用技巧
Pod 管理
- 完整配置選項
- 健康檢查機制
- 生命週期管理
Workload 資源
- Deployment 滾動更新
- StatefulSet 有狀態應用
- DaemonSet 與 Job
網路配置
- Service 類型與應用
- Ingress 路由管理
- 流量控制
儲存管理
- PV/PVC 機制
- StorageClass 動態佈建
- 資料持久化策略
配置管理
- ConfigMap 應用配置
- Secret 密鑰管理
- 多種注入方式
關鍵要點
- 掌握 kubectl 是操作 K8s 的基礎
- 理解資源生命週期與狀態轉換
- 善用標籤和選擇器進行資源管理
- 配置健康檢查確保服務可用性
- 合理設定資源限制避免資源耗盡
下一步
在第三篇文章中,我們將探討:
- 自動擴展(HPA/VPA)
- RBAC 權限管理
- Network Policy 網路策略
- Helm 套件管理
- 監控與日誌方案
- CI/CD 整合
- 生產環境最佳實踐
掌握這些核心資源操作後,您將能夠在 Kubernetes 上部署和管理各種應用!