Prometheus配置文件详解

概述

Prometheus是一个开源的系统监控和警报工具包。它的配置文件通常命名为prometheus.yml,用于配置Prometheus服务器的行为。

其配置文件主要包含以下几个部分:

  1. global: 全局配置

  2. alerting: 警报配置

  3. rule_files: 规则文件配置

  4. scrape_configs: 抓取配置(用于配置监控目标)

  5. remote_write, remote_read: 远程读写配置(用于与远程存储集成)

global(全局配置)

定义整个 Prometheus 实例的默认行为

示例:

复制代码
global:
  # 设定 Prometheus 抓取目标实例指标数据的时间间隔,默认 1m ,可按需修改,如设为 15s 实现更频繁采集 。
  scrape_interval: 15s
  # Prometheus 评估告警规则的时间间隔,默认 1m ,即每 1 分钟检查告警规则是否触发。
  evaluation_interval: 15s
  # 一次抓取请求的超时时间,默认 10s ,超时则抓取失败
  scrape_timeout: 10s
  # 与外部系统(联邦、远程存储、Alertmanager 等 )通信时,添加到度量指标数据的标签,用于标识监控源等信息。
  external_labels:
    cluster: "prod"
    region: "us-west"

rule_files(规则文件配置)

指定告警规则文件路径列表,支持通配符。Prometheus 从中读取告警规则

示例:

复制代码
rule_files:
  - "rules/alerts.yml"        # 警报规则路径
  - "rules/*.rules"           # 支持通配符

规则文件示例 (rules/alerts.yml):

复制代码
groups:
- name: example-alerts
  rules:
  - alert: HighCPU
    expr: avg(rate(node_cpu_seconds_total{mode="idle"}[5m])) < 0.2
    for: 10m
    labels:
      severity: critical
    annotations:
      summary: "高CPU使用率 ({{ $labels.instance }})"

alerting(警报配置)

关联 Alertmanager 实例

复制代码
alertmanagers:
  - scheme: http
    # 发送警报超时时间
    timeout: 10s
    # Alertmanager实例地址
    static_configs:
      - targets:
        - "127.0.0.1:9093"

scrape_configs(抓取配置)

核心部分,用于定义监控目标及数据抓取方式。

复制代码
scrape_configs:
  # Job 名称(唯一标识)
  - job_name: "prometheus"
    # 静态目标列表
    static_configs:
      # 目标地址 (host:port)
      - targets: ["localhost:9090"]

  - job_name: "node_exporter"
    # 协议 (http/https, 默认http)
    scheme: https
    # 指标路径(默认为 /metrics)
    metrics_path: /metrics
    # 请求参数
    params:
      module: [net]
    # 目标地址
    static_configs:
      - targets: ["10.0.0.1:9100", "10.0.0.2:9100"]
    # 抓取前重写标签
    relabel_configs:
      - source_labels: [__address__]
        target_label: __param_target
      - source_labels: [__param_target]
        target_label: instance
    # 抓取后重写指标标签
    metric_relabel_configs:
      - source_labels: [device]
        regex: "^(/dev/sd.).*"
        replacement: "$1"
        action: replace

remote_write&remote_read(远程读写配置)

远程写入配置(remote_write)

配置将 Prometheus 采集数据远程写入其他存储系统的参数,如:

  • url:远程存储写入地址。
  • remote_timeout:远程写入请求超时时间,默认 30s 。
  • 还包括 tls_config(TLS 配置)、basic_auth(认证配置 )、write_relabel_configs(对要远程写入数据重新标记 )等配置项。

远程读取配置(remote_read)

配置从远程存储读取数据的相关参数,与 remote_write 类似 ,如 url(读取地址) 、read_recent(是否仅读取最近数据 )、required_matchers(读取数据必须匹配的标签条件 )等。

热加载配置文件

修改了配置文件之后,我们不想重启Prometheus,想让其进行热加载配置文件,应该怎么做呢?

前提条件,启动Prometheus时需要开启热加载,需要指定该参数:--web.enable-lifecycle

访问下面的接口即可

复制代码
curl -X POST http://localhost:9090/-/reload

热加载之前可以使用promtool工具对你的配置文件修改进行检查

复制代码
[root@lb ~/prometheus]# ./promtool check config prometheus.yml
Checking prometheus.yml
 SUCCESS: prometheus.yml is valid prometheus config file syntax