Prometheus部署与配置实战指南

一、核心配置文件解析

1. prometheus.yml结构剖析

Prometheus的核心配置文件采用YAML格式,主要包含以下关键部分:

global:
  scrape_interval: 15s
  evaluation_interval: 15s

scrape_configs:
  - job_name: 'node'
    static_configs:
      - targets: ['192.168.1.100:9100', '192.168.1.101:9100']

rule_files:
  - 'alert.rules'
  - 'recording.rules'

alerting:
  alertmanagers:
    - static_configs:
        - targets: ['alertmanager:9093']

实践建议

  • 使用scrape_interval控制抓取频率,生产环境通常设置为15-60秒
  • 通过evaluation_interval设置规则评估间隔,应与告警响应时间需求匹配

2. scrape_configs详解

抓取目标配置支持多种服务发现方式:

scrape_configs:
  - job_name: 'kubernetes-nodes'
    kubernetes_sd_configs:
      - role: node
    relabel_configs:
      - source_labels: [__address__]
        regex: '(.*):10250'
        replacement: '${1}:9100'
        target_label: __address__

动态发现类型

  • Kubernetes (kubernetes_sd_configs)
  • Consul (consul_sd_configs)
  • DNS (dns_sd_configs)
  • 文件 (file_sd_configs)

二、数据抓取机制

1. Pull vs Push模式对比

图1

模式选择建议

  • 长期运行服务:优先使用Pull模式
  • 批处理任务:通过Pushgateway中转
  • 注意Pushgateway可能成为单点故障

2. 抓取参数优化

scrape_configs:
  - job_name: 'api-service'
    scrape_interval: 30s
    scrape_timeout: 10s
    metrics_path: '/metrics'
    scheme: 'https'
    tls_config:
      insecure_skip_verify: true

关键参数

  • scrape_timeout:建议设置为scrape_interval的1/3
  • metrics_path:自定义指标暴露路径
  • scheme:支持HTTP/HTTPS

三、高可用部署方案

1. 联邦集群架构

图2

配置示例:

scrape_configs:
  - job_name: 'federate'
    scrape_interval: 15s
    honor_labels: true
    metrics_path: '/federate'
    params:
      'match[]':
        - '{job="prometheus"}'
        - '{__name__=~"job:.*"}'
    static_configs:
      - targets:
        - 'prometheus-dc1:9090'
        - 'prometheus-dc2:9090'

2. 远程存储集成

推荐组合方案:

  1. Prometheus + Thanos(对象存储)
  2. Prometheus + Cortex(多租户支持)
  3. Prometheus + M3DB(分布式TSDB)

配置示例

remote_write:
  - url: "http://thanos-receive:10908/api/v1/receive"
    queue_config:
      capacity: 10000
      max_shards: 200
      min_shards: 1

四、最佳实践总结

  1. 标签设计原则

    • 避免高基数标签(如用户ID、IP地址)
    • 使用labeldrop/labelkeep过滤无用标签
  2. 规则文件管理

    rule_files:
      - '/etc/prometheus/rules/*.rules'
    • 按功能拆分规则文件(如CPU、内存、磁盘独立文件)
    • 使用recording_rules预计算复杂查询
  3. Alertmanager集成

    alerting:
      alertmanagers:
        - static_configs:
            - targets: ['alertmanager:9093']
          basic_auth:
            username: 'prometheus'
            password: 'secret'
  4. 资源限制

    global:
      scrape_samples_limit: 5000
      target_limit: 2000

通过合理配置,单个Prometheus实例可处理:

  • 每秒百万级样本
  • 数千个监控目标
  • TB级的本地存储数据

遇到性能瓶颈时,建议优先考虑:

  1. 优化标签基数
  2. 增加分片(联邦集群)
  3. 接入远程存储

添加新评论