4.1 安裝 Prometheus
Prometheus 是一個非常強大的開源監控和警報系統,專為從多種來源(包括 Docker 容器)收集和儲存指標而設計。在這堂課中,我們會詳細介紹如何使用 Prometheus 來設定容器的監控,包括安裝、設置指標收集及與 Docker 的整合。
1. 下載並安裝 Prometheus
首先,從官方網站下載最新版的 Prometheus:
wget https://github.com/prometheus/prometheus/releases/download/v2.30.3/prometheus-2.30.3.linux-amd64.tar.gz
解壓這個壓縮檔:
tar xvfz prometheus-*.tar.gz
cd prometheus-*
將二進制檔案移動到 /usr/local/bin
:
sudo mv prometheus /usr/local/bin/
sudo mv promtool /usr/local/bin/
4.2 設置 Prometheus 配置文件
Prometheus 使用配置文件 prometheus.yml
來定義 metrics 的來源和數據收集設置。創建或編輯 prometheus.yml
文件:
global:
scrape_interval: 15s # 收集 metrics 的間隔
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'cadvisor'
static_configs:
- targets: ['localhost:8080']
此配置文件包含兩個任務(job):
prometheus
: 用於從 Prometheus 自身收集 metrics。cadvisor
: 用於從 cAdvisor 收集 metrics,cAdvisor 將用於監控 Docker 容器。
5.3 啟動 Prometheus
使用建立的設定檔啟動 Prometheus:
prometheus --config.file=prometheus.yml
Prometheus 將可透過以下網址訪問:http://localhost:9090。
5.4 安裝和設定 cAdvisor
cAdvisor
(Container Advisor)是一個用於監控容器的工具,可以收集並提供 Docker 容器的指標。以下是使用此工具的步驟:
在 Docker 容器中啟動 cAdvisor
:
docker run -d \
--name=cadvisor \
--volume=/:/rootfs:ro \
--volume=/var/run:/var/run:ro \
--volume=/sys:/sys:ro \
--volume=/var/lib/docker/:/var/lib/docker:ro \
--publish=8080:8080 \
--privileged \
gcr.io/cadvisor/cadvisor:latest
cAdvisor
可以通過網址 http://localhost:8080 訪問。
5.5 更新 Prometheus 配置來支持 cAdvisor
確保 Prometheus 的配置包括 cAdvisor 的任務設定。配置範例已在上面提供。
重新啟動 Prometheus 以應用更改:
prometheus --config.file=prometheus.yml
5.6 驗證指標收集
打開 Prometheus 的 web 介面,網址是 http://localhost:9090,並確認 Prometheus 已經從 cAdvisor 收集到指標。為此,請在 Prometheus 裡執行以下請求:
container_cpu_usage_seconds_total
你應該能看到從 Docker 容器收集到的資料。
5.7 添加更多指標
你可以在 Prometheus 的配置文件中添加更多的指標,這樣能收集到更多關於容器的數據。以下是一些額外指標的範例:
- job_name: 'node'
static_configs:
- targets: ['localhost:9100']
要實現這個功能,需要安裝 node_exporter
,它提供了主機系統的狀態指標。
下載並安裝 node_exporter
:
wget https://github.com/prometheus/node_exporter/releases/download/v1.2.2/node_exporter-1.2.2.linux-amd64.tar.gz
tar xvfz node_exporter-*.tar.gz
sudo mv node_exporter-1.2.2.linux-amd64/node_exporter /usr/local/bin/
啟動 node_exporter:
node_exporter &
現在 node_exporter
可以通過 http://localhost:9100 訪問。
5.8 創建警報規則
Prometheus 支援創建警報規則,以通知管理員有問題發生。在配置文件 prometheus.yml
中新增警報規則:
rule_files:
- "alert.rules"
alerting:
alertmanagers:
- static_configs:
- targets:
- "localhost:9093"
創建一個 alert.rules
文件,示範規則如下:
groups:
- name: example
rules:
- alert: HighCPUUsage
expr: container_cpu_usage_seconds_total{job="cadvisor"} > 0.85
for: 1m
labels:
severity: warning
annotations:
summary: "檢測到高 CPU 使用率"
description: "容器在 1 分鐘內使用超過 85% 的 CPU。"
GO TO FULL VERSION