kube-prometheus-stack,並在 Grafana 儀表板中即時查看 Node 與 Pod 的運算資源狀態。當微服務集群擴展到數十台 Node、數百個 Pod 時,傳統的「登入機器看 log」或單純依賴 kubectl top 已經完全不夠用。
現代雲原生架構講求可觀測性的三大支柱:
| 支柱 | 核心內容 | 典型開源解決方案 |
|---|---|---|
| Metrics(指標) | 可聚合的數值型數據(如 CPU 使用率、記憶體消耗、每秒請求數 QPS) | Prometheus |
| Logs(日誌) | 帶有時間戳記的文字事件記錄(如應用程式報錯堆疊 Error Stack) | Loki / Fluentd / ELK |
| Traces(分散式追蹤) | 單一請求跨越多個微服務的完整呼叫鏈路與延遲分析 | Jaeger / OpenTelemetry |
今天我們將聚焦在最核心、最關鍵的第一支柱:Metrics 監控。
Prometheus 是繼 Kubernetes 之後,CNCF(雲原生運算基金會)第二個正式畢業的旗艦專案。
/metrics 端點發送 HTTP 請求抓取最新數據。社群將 Prometheus、Grafana、Node Exporter、Alertmanager 打包成了一套極其強大的 Chart——kube-prometheus-stack。
helm repo add prometheus-community [https://prometheus-community.github.io/helm-charts](https://prometheus-community.github.io/helm-charts)
helm repo update
我們建立一個獨立的命名空間 monitoring 來運行監控元件:
helm install prometheus-stack prometheus-community/kube-prometheus-stack \
--namespace monitoring \
--create-namespace
小提醒:監控套件元件較多,初次下載映像檔與啟動約需 1 至 3 分鐘。
檢查監控 Pod 是否全數進入 Running:
kubectl get pods -n monitoring
取得 Grafana 的登入密碼(預設帳號為 admin,密碼存放於 Secret 中):
kubectl get secret --namespace monitoring prometheus-stack-grafana -o jsonpath="{.data.admin-password}" | base64 --decode ; echo
使用端口轉發將 Grafana 服務映射到本地:
kubectl port-forward --namespace monitoring svc/prometheus-stack-grafana 3000:80
保持終端機開啟,打開瀏覽器訪問 http://localhost:3000:
admin 與剛剛解碼取得的密碼登入。如果你想直接查詢 Prometheus 指標,也可以將 Prometheus Server 轉發到本地:
kubectl port-forward --namespace monitoring svc/prometheus-stack-kube-prom-prometheus 9090:9090
打開瀏覽器訪問 http://localhost:9090,在 Expression 搜尋框輸入以下常用 PromQL 查詢:
查詢所有節點的 CPU 空閒率百分比:
100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)
查詢當前正在運行的 Pod 總數:
count(kube_pod_status_phase{phase="Running"})
今天我們成功在 Kubernetes 集群上建置了企業級的監控體系:
kube-prometheus-stack 快速拉起全套監控基礎設施。有了指標監控後,當系統發生嚴重錯誤(例如 Pod 重複 Crash 或記憶體不足 OOMKilled)時,我們該去哪裡集中搜尋與分析散落在各處的容器日誌?
明天 Day 25,我們將學習日誌收集的中樞神經:「集中式日誌管理:使用 Grafana Loki + Promtail 收集 Pod 日誌」!