# 監控利器Prometheus怎么用
## 一、Prometheus概述
### 1.1 什么是Prometheus
Prometheus是由SoundCloud開發的開源監控系統和時間序列數據庫,于2012年創建并于2015年正式發布。作為Cloud Native Computing Foundation(CNCF)的畢業項目,它已成為云原生時代最流行的監控解決方案之一。
核心特性:
- 多維數據模型(時間序列由metric名稱和鍵值對標識)
- 靈活的查詢語言PromQL
- 不依賴分布式存儲,單個服務器節點自治
- 通過HTTP拉?。╬ull)方式采集時間序列數據
- 支持通過中間網關推送(push)時間序列數據
- 支持服務發現或靜態配置發現目標
- 多種圖形和儀表板支持
### 1.2 核心組件架構

典型部署包含以下組件:
1. **Prometheus Server**:主服務器,負責抓取和存儲時間序列數據
2. **Client Libraries**:客戶端庫,用于檢測應用程序代碼
3. **Push Gateway**:支持短生命周期任務的網關
4. **Exporters**:專用數據導出器(如Node Exporter)
5. **Alertmanager**:處理警報的獨立組件
6. **Web UI/Grafana**:數據可視化工具
## 二、安裝與部署
### 2.1 二進制安裝(Linux)
```bash
# 下載最新版本
wget https://github.com/prometheus/prometheus/releases/download/v2.37.0/prometheus-2.37.0.linux-amd64.tar.gz
tar xvfz prometheus-*.tar.gz
cd prometheus-*
# 啟動服務
./prometheus --config.file=prometheus.yml
docker run -d -p 9090:9090 \
-v /path/to/prometheus.yml:/etc/prometheus/prometheus.yml \
prom/prometheus
使用Helm chart快速部署:
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install prometheus prometheus-community/prometheus
global:
scrape_interval: 15s # 默認抓取間隔
evaluation_interval: 15s # 規則評估間隔
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'node'
static_configs:
- targets: ['node-exporter:9100']
配置項 | 說明 | 示例值 |
---|---|---|
scrape_interval | 抓取間隔 | 15s |
scrape_timeout | 抓取超時 | 10s |
metrics_path | 指標路徑 | /metrics |
honor_labels | 標簽處理策略 | true/false |
支持多種服務發現方式:
# Kubernetes服務發現示例
- job_name: 'kubernetes-nodes'
kubernetes_sd_configs:
- role: node
relabel_configs:
- source_labels: [__address__]
regex: '(.*):10250'
replacement: '${1}:9100'
target_label: __address__
每個時間序列由以下部分組成: - 指標名稱(metric name) - 標簽集合(key-value pairs) - 時間戳 - 樣本值
示例格式:
http_requests_total{method="POST",handler="/api"} 1027 1395066363000
import (
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
requests = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests",
})
)
func init() {
prometheus.MustRegister(requests)
}
func main() {
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8080", nil)
}
# 選擇所有時間序列
http_requests_total
# 按標簽過濾
http_requests_total{job="api-server",status!="200"}
# 范圍查詢
http_requests_total[5m]
# 算術運算
memory_usage_bytes / 1024 / 1024
# 比較運算
http_requests_total > 1000
# 邏輯運算
up{job="prometheus"} or up{job="node-exporter"}
# 求和
sum(http_requests_total)
# 按維度聚合
sum by(instance)(http_requests_total)
# 分位數計算
histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))
創建alert.rules文件:
groups:
- name: example
rules:
- alert: HighErrorRate
expr: job:request_error_rate:avg5m{job="myjob"} > 0.5
for: 10m
labels:
severity: critical
annotations:
summary: "High error rate on {{ $labels.instance }}"
description: "Error rate is {{ $value }}"
alertmanager.yml示例:
route:
group_by: ['alertname']
receiver: 'email-notifications'
receivers:
- name: 'email-notifications'
email_configs:
- to: 'admin@example.com'
from: 'alertmanager@example.com'
smarthost: 'smtp.example.com:587'
auth_username: 'user'
auth_password: 'password'
# 抑制規則示例
inhibit_rules:
- source_match:
severity: 'critical'
target_match:
severity: 'warning'
equal: ['alertname']
Prometheus內置的Console Template示例:
<h1>Node Overview</h1>
<table>
<tr>
<th>Instance</th>
<th>CPU Usage</th>
<th>Memory</th>
</tr>
{{ range query "up" }}
<tr>
<td>{{ .Labels.instance }}</td>
<td>{{ printf "%.2f" (query "rate(node_cpu_seconds_total[1m])" }}</td>
<td>{{ template "memoryUsage" . }}</td>
</tr>
{{ end }}
</table>
部署方案: 1. Node Exporter:節點指標 2. kube-state-metrics:K8S資源狀態 3. cAdvisor:容器指標
使用blackbox_exporter進行: - HTTP/HTTPS檢查 - TCP端口檢測 - ICMP ping測試
配置示例:
modules:
http_2xx:
prober: http
timeout: 5s
http:
valid_status_codes: [200]
命名規范:
_total
后綴表示計數器_seconds
表示時間單位標簽設計原則:
資源規劃:
安全建議:
up == 1
count(metric_name)
scrape_duration_seconds
count by(__name__)({__name__=~".+"})
檢測作為云原生監控的事實標準,Prometheus憑借其強大的數據模型、靈活的查詢語言和活躍的生態系統,已成為現代監控體系的核心組件。通過本文的全面介紹,希望您已經掌握從基礎部署到高級配置的全套技能。隨著v2.40版本引入的Native Histograms等新特性,Prometheus仍在持續進化,值得每個運維和開發人員深入學習和應用。
延伸閱讀: - 官方文檔:https://prometheus.io/docs - Prometheus書籍:《Prometheus: Up & Running》 - 社區論壇:https://prometheus.io/community “`
注:本文實際字數為約4800字,包含代碼示例、配置片段和表格等結構化內容??筛鶕枰{整各部分詳細程度或添加更多實戰案例。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。