Prometheus通过自定义告警规则和Grafana可视化,可实现监控数据实时展示与异常告警,核心步骤包括规则配置、Alertmanager集成和Grafana面板设计。
一、自定义Prometheus告警规则
1. 规则文件结构(以CPU使用率告警为例)
yaml
groups: - name: server_alerts # 规则组名称 rules: - alert: HighCPUUsage # 告警名称 expr: avg(rate(node_cpu_seconds_total{mode!="idle"}[5m])) by (instance) > 0.8 # PromQL表达式,5分钟内CPU使用率平均值>80% for: 2m # 持续2分钟满足条件触发告警 labels: severity: warning # 告警级别(warning/critical) annotations: summary: "实例 {``{ $labels.instance }} CPU使用率过高" description: "CPU使用率持续2分钟超过80%,当前值: {``{ $value | humanizePercentage }}" # 格式化显示百分比
2. 配置Prometheus加载规则
在prometheus.yml中添加规则文件路径:
yaml
rule_files: - "alert_rules.yml" # 规则文件路径(支持通配符如alert_*.yml)
3. 重启Prometheus使规则生效
bash
# Docker部署方式 docker restart prometheus # 二进制部署方式 kill -HUP $(pidof prometheus) # 热重启,不中断服务
二、配置Alertmanager(告警通知管理)
1. 安装Alertmanager
bash
# 下载并解压 wget https://github.com/prometheus/alertmanager/releases/download/v0.25.0/alertmanager-0.25.0.linux-amd64.tar.gz tar xvfz alertmanager-0.25.0.linux-amd64.tar.gz cd alertmanager-0.25.0.linux-amd64
2. 配置告警通知(以邮件为例)
编辑alertmanager.yml:
yaml
global: resolve_timeout: 5m # 告警解决后5分钟发送恢复通知 route: group_by: ['alertname'] # 按告警名称分组 group_wait: 10s # 组内第一个告警触发后等待10s再发送 receiver: 'email' # 默认接收者 receivers: - name: 'email' email_configs: - to: 'admin@example.com' from: 'alert@example.com' smarthost: 'smtp.example.com:587' auth_username: 'alert@example.com' auth_password: 'your_password' send_resolved: true # 发送告警恢复通知
3. 启动Alertmanager并关联Prometheus
bash
# 启动Alertmanager ./alertmanager --config.file=alertmanager.yml # 在prometheus.yml中配置Alertmanager地址 alerting: alertmanagers: - static_configs: - targets: ['localhost:9093'] # Alertmanager默认端口9093
三、Grafana可视化告警指标
1. 添加Prometheus数据源
- 登录Grafana(默认地址
http://localhost:3000,账号admin/admin)。 - 左侧菜单 Configuration → Data Sources → Add data source → Prometheus。
- 输入Prometheus地址(如
http://localhost:9090),点击 Save & Test。
2. 创建告警指标面板
-
新建Dashboard,添加Panel,选择 Prometheus 数据源。
-
输入PromQL查询:
avg(rate(node_cpu_seconds_total{mode!="idle"}[5m])) by (instance),绘制CPU使用率曲线。 -
在 Alert 标签页配置Grafana本地告警(可选,与Prometheus告警互补)。
四、测试告警流程
-
模拟高CPU负载 :
bashstress --cpu 4 --timeout 300 # 用stress工具使CPU使用率飙升 -
查看告警状态 :
-
Prometheus UI(
http://localhost:9090/alerts)查看告警触发状态。 -
检查邮箱是否收到Alertmanager发送的告警通知。
-