Prometheus + Grafana 监控系统零基础上手指南(监控到告警闭环篇)

前面几章我们完成了 Prometheus 的安装配置、Grafana 可视化和 Node Exporter 部署。本章将介绍告警规则的配置与 AlertManager 的使用,实现从监控到告警的完整闭环。

一、AlertManager 概述

什么是 AlertManager

AlertManager 是 Prometheus 监控体系中的告警管理组件,负责处理 Prometheus Server 发送的告警,实现告警的分发、抑制、静默和通知。

工作原理

┌─────────────┐     告警     ┌─────────────────┐     通知     ┌────────────┐
│ Prometheus  │ ──────────▶ │  AlertManager   │ ──────────▶ │  飞书/邮件 │
│   Server    │              │                 │              │  钉钉等    │
└─────────────┘              └─────────────────┘              └────────────┘

Prometheus Server 根据告警规则检测指标,当条件满足时将告警发送给 AlertManager。AlertManager 进行分组、抑制、静默处理后,通过配置好的通知渠道发送。

核心功能

  • 分组(Grouping):将相似告警合并,避免告警风暴
  • 抑制(Inhibition):当某告警触发时,自动抑制相关告警
  • 静默(Silence):在特定时间段静默某些告警
  • 路由(Routing):根据标签将告警路由到不同接收人

二、安装 AlertManager

Docker 部署

docker run -d \
  --name=alertmanager \
  -p 9093:9093 \
  -p 9094:9094 \
  -v alertmanager-data:/alertmanager \
  prom/alertmanager:v0.27.0

访问地址:http://localhost:9093

二进制部署

wget https://github.com/prometheus/alertmanager/releases/download/v0.27.0/alertmanager-0.27.0.linux-amd64.tar.gz
tar -xzf alertmanager-0.27.0.linux-amd64.tar.gz
cd alertmanager-0.27.0.linux-amd64
./alertmanager --config.file=alertmanager.yml --storage.path=/data

三、基础配置

alertmanager.yml

global:
  # 告警解决超时时间
  resolve_timeout: 5m
  # SMTP 配置(邮件通知)
  smtp_smarthost: 'smtp.example.com:587'
  smtp_from: '[email protected]'
  smtp_auth_username: '[email protected]'
  smtp_auth_password: 'your-password'

# 告警路由配置
route:
  # 按 alertname 分组
  group_by: ['alertname']
  # 初始等待时间
  group_wait: 10s
  # 告警间等待时间
  group_interval: 10s
  # 重复告警间隔
  repeat_interval: 12h
  # 默认接收者
  receiver: 'default-receiver'
  # 子路由
  routes:
    - match:
        severity: critical
      receiver: 'critical-receiver'
      continue: true
    - match:
        severity: warning
      receiver: 'warning-receiver'

# 接收者配置
receivers:
  - name: 'default-receiver'
    email_configs:
      - to: '[email protected]'
        send_resolved: true

  - name: 'critical-receiver'
    email_configs:
      - to: '[email protected]'
    webhook_configs:
      - url: 'http://your-webhook-endpoint/dingtalk'

# 告警抑制规则
inhibit_rules:
  - source_match:
      severity: 'critical'
    target_match:
      severity: 'warning'
    equal: ['instance']

Prometheus 配置

prometheus.yml 中添加 AlertManager:

alerting:
  alertmanagers:
    - static_configs:
        - targets:
            - 'localhost:9093'

四、告警规则配置

规则文件结构

在 Prometheus 中创建告警规则文件:

groups:
  - name: instance_alerts
    rules:
      # 实例宕机告警
      - alert: InstanceDown
        expr: up == 0
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "实例 {{ $labels.instance }} 宕机"
          description: "实例 {{ $labels.instance }} 已离线超过 1 分钟"

      # CPU 使用率过高
      - alert: HighCPUUsage
        expr: 100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "CPU 使用率过高"
          description: "{{ $labels.instance }} CPU 使用率 {{ $value }}%"

      # 内存使用率过高
      - alert: HighMemoryUsage
        expr: (node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes) / node_memory_MemTotal_bytes * 100 > 85
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "内存使用率过高"
          description: "{{ $labels.instance }} 内存使用率 {{ $value }}%"

加载规则文件

prometheus.yml 中引用规则文件:

rule_files:
  - "/etc/prometheus/rules/*.yml"

告警状态说明

状态 说明
Inactive 告警条件未满足
Pending 条件满足,等待 for 持续时间
Firing 告警触发,发送通知

五、告警状态管理

查看告警状态

访问 AlertManager Web UI(http://localhost:9093):

  • Alerts:当前告警列表
  • Silence:静默规则
  • Status:运行时状态

静默配置

通过 Web UI 静默:

  1. 访问 http://localhost:9093
  2. 点击 “Silence” → “New Silence”
  3. 填写匹配条件和持续时间

通过配置静默:

- match:
    severity: warning
  id: maintenance-window-001
  starts_at: "2024-12-25 00:00:00"
  ends_at: "2024-12-25 06:00:00"
  created_by: admin
  comment: "计划维护窗口"

六、通知渠道配置

飞书 Webhook

receivers:
  - name: 'feishu-receiver'
    webhook_configs:
      - url: 'https://open.feishu.cn/open-apis/bot/v2/hook/YOUR_HOOK_ID'
        send_resolved: true

钉钉 Webhook

receivers:
  - name: 'dingtalk-receiver'
    webhook_configs:
      - url: 'https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN'
        send_resolved: true

Slack

receivers:
  - name: 'slack-receiver'
    slack_configs:
      - api_url: 'https://hooks.slack.com/services/XXX/YYY/ZZZ'
        channel: '#alerts'
        send_resolved: true

七、运维命令

# 热重载配置
curl -X POST http://localhost:9093/-/reload

# 查看版本
curl http://localhost:9093/api/v1/status/version

# 检查告警状态
curl http://localhost:9093/api/v1/alerts

# 手动静默
amtool silence add alertname=InstanceDown --duration=1h

八、常见问题排查

1. 告警未发送

# 检查日志
docker logs -f alertmanager

# 验证告警路由
curl http://localhost:9093/api/v1/alerts | jq

2. 通知失败

  • 检查 Webhook 地址是否正确
  • 确认防火墙放行
  • 验证时间格式(RFC3339)

九、告警分级建议

级别 触发条件 通知方式
P0 - 紧急 服务完全不可用 电话 + 短信
P1 - 高 服务降级 即时通讯
P2 - 中 性能下降 邮件
P3 - 低 潜在风险 邮件

十、Grafana 告警配置

Grafana 提供内置告警功能,适合简单的告警场景:

创建告警规则

  1. 进入 AlertingAlert rules
  2. 点击 New alert rule
  3. 配置查询和条件

告警条件示例

CPU 使用率超过 80% 持续 5 分钟:

1 - avg(rate(node_cpu_seconds_total{mode="idle"}[5m])) by (instance) > 0.8

Grafana vs AlertManager

场景 推荐方案
简单阈值告警 Grafana 内置告警
跨数据源告警 Grafana 内置告警
复杂 PromQL 告警 Prometheus + AlertManager
高可用要求 Prometheus + AlertManager 集群

十一、Docker Compose 一键部署

使用 Docker Compose 快速部署完整监控体系:

version: '3.8'

services:
  prometheus:
    image: prom/prometheus:v2.51.0
    ports:
      - "9090:9090"
    volumes:
      - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
      - ./data/prometheus:/prometheus
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--storage.tsdb.path=/prometheus'

  alertmanager:
    image: prom/alertmanager:v0.27.0
    ports:
      - "9093:9093"
    volumes:
      - ./alertmanager/alertmanager.yml:/etc/alertmanager/alertmanager.yml

  grafana:
    image: grafana/grafana:10.4.0
    ports:
      - "3000:3000"
    environment:
      - GF_SECURITY_ADMIN_USER=admin
      - GF_SECURITY_ADMIN_PASSWORD=admin123

networks:
  default:
    name: monitoring

启动命令

docker compose up -d
docker compose logs -f prometheus
docker compose down

十二、Kubernetes 部署方案

使用 Helm 在 Kubernetes 中部署:

helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install prometheus prometheus-community/kube-prometheus-stack

端口转发访问

kubectl port-forward svc/prometheus-grafana 3000
kubectl port-forward svc/prometheus-kube-prometheus-stack-alertmanager 9093

本章小结

本章完成了从监控到告警的完整闭环配置。通过 Prometheus 告警规则和 AlertManager,我们实现了:

  • 告警检测与触发
  • 告警分组与路由
  • 多渠道通知
  • 告警静默与抑制

结合 Grafana 告警和 Docker Compose / Kubernetes 部署方案,可以快速搭建完整的生产级监控告警体系。

📚 延伸阅读


本站由 时空 使用 Stellar 搭建。