Grafana 本身不存指标,它负责查询、绘图和告警。这篇记从接入 Prometheus 到做出能用的看板,以及两套告警体系(Grafana Alerting 与 Prometheus Alertmanager)共存时的取舍。

起服务

1
2
3
4
5
6
7
8
# 数据目录挂到卷上,否则容器删了看板和用户一起没
docker volume create grafana-storage

docker run -d --name=grafana -p 3000:3000 \
-v grafana-storage:/var/lib/grafana \
-v /opt/grafana/provisioning:/etc/grafana/provisioning:ro \
-e GF_PATHS_PROVISIONING=/etc/grafana/provisioning \
grafana/grafana-enterprise
  • 3000 是默认 HTTP 端口,管理员账号是 admin(用户 ID 为 1,忘了密码可以用 grafana cli admin reset-admin-password 重置);/var/lib/grafana 存 SQLite 库、插件和看板目录;环境变量 GF_<SECTION>_<KEY> 可以覆盖 grafana.ini 里的任意配置,这里用它显式指定 provisioning 目录,省得猜路径;官方默认镜像是 enterprise 版,免费且包含 OSS 全部功能,纯 OSS 换成 grafana/grafana。

数据源

添加 Prometheus 时最容易踩的是 URL:容器里的 localhost 指向容器自己。

1
2
http://prometheus:9090      同一个 docker network 里用服务名,首选
http://172.17.0.1:9090 或者宿主在 docker0 上的地址

另一个必须对齐的参数是 Scrape interval(默认 15s),要和 Prometheus 的 scrape_interval 一致,因为 $__rate_interval 按它计算。

1
2
$__rate_interval = max($__interval + scrape_interval, 4 * scrape_interval)
scrape_interval 取值顺序:查询里的 Min step > 数据源的 Scrape interval

Prometheus 实际是 1m 而这里留 15s,rate() 的窗口就偏小,典型症状是图上断点或 no data;各 target 间隔不一致时按最长的填。

数据源可以落到文件里做版本管理:

1
2
3
4
5
6
7
8
9
10
11
12
# /opt/grafana/provisioning/datasources/prometheus.yml
apiVersion: 1
datasources:
- name: Prometheus
type: prometheus
access: proxy # 由 Grafana 服务端代理查询,最常用
url: http://prometheus:9090
isDefault: true
jsonData:
httpMethod: POST
timeInterval: 30s # 对应上面的 Scrape interval
prometheusType: Prometheus

provisioning 出来的数据源在 UI 里是只读的,改参数要改文件再重启。

模板变量与面板

  • Query:从数据源查标签值,主机名场景最常用,经典写法是 label_values(node_uname_info, instance);新版 UI 里对应 Query type 选 Label values,老写法被标为 classic。
  • Custom:手工维护固定列表,如 1h,6h,24h,7d;Interval 专供时间聚合粒度切换;Data source 用于多套 Prometheus 环境共用一张看板。
    1
    2
    3
    rate(node_network_receive_bytes_total{instance="$instance"}[$__rate_interval])
    $__interval 按时间范围和面板宽度算出的聚合步长
    $__rate_interval 专给 rate()/increase() 用,保证窗口里至少有 4 个采样点
    显示层三件事:Unit 选对(bytes/percent/seconds)、Thresholds 改默认值(默认基线绿、80 变红,模式 Absolute)、同一面板里不同 series 需要区别对待时用 Overrides。

常用面板查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# CPU 使用率(先按核求和,再算非 idle 占比)
100 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[$__rate_interval])) * 100
# 内存使用率
(1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100
# 磁盘使用率(按挂载点过滤伪文件系统)
100 - node_filesystem_avail_bytes{fstype!~"tmpfs|overlay|squashfs"} / node_filesystem_size_bytes{fstype!~"tmpfs|overlay|squashfs"} * 100
# 网卡流量(bit/s)
rate(node_network_receive_bytes_total{device!~"lo|veth.*"}[$__rate_interval]) * 8
# 容器资源(cAdvisor)
sum by (name) (rate(container_cpu_usage_seconds_total{image!=""}[$__rate_interval]))
sum by (name) (container_memory_working_set_bytes{image!=""})
# 接口 QPS 与 P95 延迟(换成应用自己的指标名)
sum by (handler) (rate(http_requests_total[$__rate_interval]))
histogram_quantile(0.95, sum by (le, handler) (rate(http_request_duration_seconds_bucket[$__rate_interval])))

Grafana 统一告警

一条 Alert rule 由四部分组成:Query(可多个、可跨数据源)、Expression(Reduce / Math / Resample 或 Classic condition)、条件(Evaluate every / Pending period / Keep firing for)、通知。状态流转是 Normal → Pending → Alerting → Recovering → Normal(Resolved),只有 Alerting 和 Normal(Resolved) 会发出通知;Pending period 等价于 Prometheus 的 for,Keep firing for 用来压制反复触发。

1
2
3
4
5
6
# Advanced 模式下的常见写法
A: 100 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100
B: Reduce A, function = Last
C: Threshold B, Is above 90 把 C 设为 alert condition
# 用 instant query 直接出结果时不需要 Reduce
A: up{job="node"} == 0 把 A 设为 alert condition,Evaluate every 1m / Pending 3m

Reduce 的聚合函数是 Min、Max、Mean、Median、Sum、Count、Last,阈值之外也可以写 $B > 70 这类 Math 表达式;规则名会成为告警实例的 alertname 标签。告警只支持固定的相对时间范围(now-24h: now),不支持绝对时间和 now/d 这种半相对写法。

  • Contact points 是发送通道,一个 contact point 可以挂多个 integration;内置 DingDing、WeCom、Email、Slack、Telegram、Webhook,飞书没有内置类型,走 Webhook 自己拼 body。
  • Notification policies 是一棵树,根是 Default policy,每个节点用标签匹配器(=、!=、=~、!~,多个之间是 AND)决定是否接收;路由从根往下走,命中最深的子策略后不再看兄弟节点,需要就开 Continue matching siblings;子策略默认继承父级的 contact point、分组和 timing。
  • Silence 与 Mute timings 都只挡通知、不停止评估:前者按标签匹配并指定固定起止时间(发布窗口),后者是挂在策略上的周期性区间(固定维护时段),且优先于 Active time intervals。

两套体系怎么选

  • Prometheus Alerting + Alertmanager:规则和指标同源,PromQL 描述条件最直接,适合纯指标告警;代价是要单独维护 Alertmanager 的路由、抑制和静默。
  • Grafana Alerting:一个条件里能跨数据源(PromQL 指标 + Loki 日志),路由、静默、静音时段都能在 UI 里配,和看板共用一套 contact points。
  • 两者可以共存:Prometheus 侧的告警在 Grafana 里是只读展示,Grafana 自己的规则存在 Grafana 库里。实践上把告警收敛到一边,另一边只看,否则同一件事会收到两条通知。

用 provisioning 做版本管理

1
2
3
4
5
6
7
8
9
10
11
12
13
# /opt/grafana/provisioning/dashboards/default.yml
apiVersion: 1
providers:
- name: default
orgId: 1
folder: ''
type: file
disableDeletion: false # 允许删除已下线的看板
updateIntervalSeconds: 30 # 扫描 JSON 变更的间隔
allowUiUpdates: false # 禁止 UI 改动回写,避免文件和库不一致
options:
path: /etc/grafana/dashboards
foldersFromFilesStructure: true
  • 看板 JSON 从 UI 导出后丢进 path 目录,Grafana 启动时和扫描周期内自动同步。
  • 改完 provisioning 文件要重启 Grafana;文件里出现非法的 contact point 类型会让 Grafana 直接起不来。

注意事项

  • 面板 no data:先查数据源 URL 和 Scrape interval,再确认变量选中的 instance 在 Prometheus 里存在。
  • 告警一直 Pending 不 firing:Pending period 比数据点间隔还长,或评估间隔大于数据步长。
  • 通知相关问题:确认 contact point 至少挂了一个 integration 且被规则或策略引用;告警忽上忽下刷通知则加长 Pending period 或设置 Keep firing for。