Prometheus监控体系架构概述
Prometheus是CNCF孵化的开源监控告警系统,采用拉取(Pull)模式采集指标数据,通过PromQL查询语言实现灵活的时序数据查询。其核心组件包括Prometheus Server(数据采集与存储)、Alertmanager(告警处理)、Pushgateway(短任务指标推送)和各类Exporter(指标暴露器)。与传统的StatsD+Graphite推送模式不同,Prometheus主动轮询各Target采集指标,便于发现采集失败和监控目标动态变化。
一个典型的监控拓扑:node_exporter暴露主机CPU、内存、磁盘等系统指标,应用通过client_lib暴露业务指标,Prometheus定期拉取并存储为时序数据库,Alertmanager根据规则触发告警通知,Grafana连接Prometheus数据源做可视化展示。
Prometheus安装与核心配置
使用Docker快速部署Prometheus,配合node_exporter采集主机指标:
# docker-compose.yml
version: '3'
services:
prometheus:
image: prom/prometheus:v2.51.0
ports:
- "9090:9090"
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
- ./alerts.yml:/etc/prometheus/alerts.yml
- prometheus_data:/prometheus
command:
- '--config.file=/etc/prometheus/prometheus.yml'
- '--storage.tsdb.retention.time=30d'
node_exporter:
image: prom/node-exporter:v1.7.0
ports:
- "9100:9100"
network_mode: host
alertmanager:
image: prom/alertmanager:v0.27.0
ports:
- "9093:9093"
volumes:
- ./alertmanager.yml:/etc/alertmanager/alertmanager.yml
grafana:
image: grafana/grafana:10.4.0
ports:
- "3000:3000"
volumes:
- grafana_data:/var/lib/grafana
environment:
- GF_SECURITY_ADMIN_PASSWORD=admin
volumes:
prometheus_data:
grafana_data:
prometheus.yml核心配置文件定义采集目标和规则文件:
global:
scrape_interval: 15s
evaluation_interval: 15s
rule_files:
- alerts.yml
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'node'
static_configs:
- targets: ['localhost:9100']
labels:
env: 'production'
- job_name: 'app'
static_configs:
- targets: ['app:8080']
metrics_path: /metrics
scrape_interval: 10s
scrape_interval控制全局采集间隔,可在每个job级别单独覆盖。labels字段为指标附加静态标签,便于后续按环境、机房等维度聚合查询。
PromQL查询语言核心语法
PromQL是Prometheus的查询语言,支持瞬时查询、范围查询和聚合运算。几个常用查询模式:
# 瞬时查询:当前CPU使用率
100 - (avg by(instance)(rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)
# 范围查询:过去1小时内存使用率
(node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes) / node_memory_MemTotal_bytes * 100
# 聚合查询:各实例磁盘使用率
(node_filesystem_size_bytes - node_filesystem_free_bytes) / node_filesystem_size_bytes * 100
# 多维度聚合:按env标签分组计算平均请求量
sum by(env)(rate(http_requests_total[5m]))
# 直方图分位数:P99响应时间
histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m]))
rate函数计算计数器指标的增长速率,[5m]表示基于过去5分钟数据计算。histogram_quantile从直方图桶中计算分位数,常用于延迟P99/P95监控。by子句按指定标签维度分组聚合,without子句则排除指定标签后聚合。
告警规则配置与Alertmanager联动
告警规则定义在独立的YAML文件中,Prometheus定期评估规则,满足条件时将告警推送到Alertmanager:
groups:
- name: host_alerts
rules:
- alert: HighCpuUsage
expr: 100 - (avg by(instance)(rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80
for: 5m
labels:
severity: critical
annotations:
summary: "CPU使用率过高 {{ $labels.instance }}"
description: "CPU使用率 {{ $value }}% 超过80%,持续5分钟"
- alert: DiskSpaceLow
expr: (node_filesystem_free_bytes / node_filesystem_size_bytes * 100) < 10
for: 10m
labels:
severity: warning
annotations:
summary: "磁盘空间不足 {{ $labels.instance }}"
description: "磁盘剩余空间 {{ $value }}% 低于10%"
- alert: ServiceDown
expr: up == 0
for: 2m
labels:
severity: critical
annotations:
summary: "服务不可达 {{ $labels.job }}"
description: "{{ $labels.instance }} 已离线超过2分钟"
for字段设置告警等待时间,避免短暂波动触发误报。severity标签区分告警级别,Alertmanager可根据级别路由到不同的通知渠道。$labels和$value模板变量在告警通知中插入实例名和当前指标值。
Alertmanager配置告警路由和通知方式:
route:
receiver: 'default'
group_by: ['alertname', 'env']
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
routes:
- match:
severity: critical
receiver: 'pagerduty'
- match:
severity: warning
receiver: 'email'
receivers:
- name: 'default'
webhook_configs:
- url: 'http://dingtalk:8060/send'
- name: 'pagerduty'
webhook_configs:
- url: 'https://events.pagerduty.com/integration/xxx/enqueue'
- name: 'email'
email_configs:
- to: 'ops@example.com'
from: 'alert@example.com'
smarthost: 'smtp.example.com:587'
group_by控制告警合并维度,相同alertname和env的告警合并为一条通知。group_wait设置初次告警等待时间,group_interval设置同组告警间隔,repeat_interval设置重复通知间隔防止告警风暴。
Grafana数据源配置与Dashboard搭建
Grafana连接Prometheus作为数据源后,可以创建可视化Dashboard。关键配置步骤:
# 1. 添加数据源
# Grafana -> Configuration -> Data Sources -> Add Prometheus
# URL: http://prometheus:9090
# Access: proxy
# 2. 创建Dashboard变量(支持动态切换)
# 变量名: $instance
# 查询: label_values(node_cpu_seconds_total, instance)
# 3. Panel查询示例:CPU使用率面板
# Query: 100 - (avg by(instance)(rate(node_cpu_seconds_total{mode="idle", instance=~"$instance"}[5m])) * 100)
# Legend: {{instance}}
# Format: Time series
Dashboard变量(Variables)支持下拉选择,配合实例名标签实现多机切换。实例正则匹配instance=~"$instance"让查询随变量选择动态变化。
推荐的Dashboard面板布局:顶部放单值面板展示关键指标概览(可用率、P99延迟、QPS),中部放时序图展示趋势变化,底部放表格面板展示实例明细。通过阈值线(Thresholds)在图表上标注告警线,低于绿色线为正常,高于红色线为告警状态。
监控指标设计最佳实践
监控指标的设计需要遵循USE原则(Utilization、Saturation、Errors)和RED原则(Rate、Errors、Duration)。USE适用于资源监控,RED适用于服务监控。
应用层面暴露自定义指标时,建议使用Prometheus官方client库的标准指标类型:
from prometheus_client import Counter, Histogram, Gauge
# Counter:单调递增计数器,用于请求量、错误量
requests_total = Counter('http_requests_total', 'Total HTTP requests', ['method', 'path'])
# Histogram:直方图,用于延迟分布
request_duration = Histogram('http_request_duration_seconds', 'Request duration',
buckets=[0.01, 0.05, 0.1, 0.5, 1, 2, 5, 10])
# Gauge:可增可减的仪表盘,用于队列长度、连接数
active_connections = Gauge('active_connections', 'Active connections')
# 使用示例
@app.route('/api/data')
def handle_request():
with request_duration.time():
requests_total.labels(method='GET', path='/api/data').inc()
active_connections.inc()
# 业务处理
active_connections.dec()
return result
Counter类型只增不减适合统计总量,Histogram分桶记录分布适合延迟监控,Gauge可增可减适合瞬时状态。三种类型配合使用可以覆盖绝大多数监控场景。指标命名使用snake_case并带单位后缀(如_seconds、_bytes),便于跨团队协作时理解。
原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/prometheus-jian-kong-gao-jing-ti-xi-da-jian-grafana-ke-shi/