Prometheus 配置 HTTPS 自签名证书抓取目标的具体步骤是什么

文章导读
配置 Prometheus 通过 HTTPS 抓取自签名证书目标,核心是在 scrape_config 中指定 scheme 为 https 并正确配置 tls_config。推荐生产环境配置 CA 证书验证,测试环境可临时跳过验证。
📋 目录
  1. A 1. 生成与分发证书
  2. B 2. 目标服务配置 HTTPS
  3. C 3. Prometheus 抓取配置
  4. D 4. 验证与排查
  5. E 5. 常见坑与风险
  6. F 参考文档
A A

配置 Prometheus 通过 HTTPS 抓取自签名证书目标,核心是在 scrape_config 中指定 scheme 为 https 并正确配置 tls_config。推荐生产环境配置 CA 证书验证,测试环境可临时跳过验证。

先说结论:该方案适合内部可信网络环境,需先生成证书并修改抓取配置,最后验收 targets 状态。

  • 适合:自建监控体系或非公网暴露的指标服务
  • 先准备:OpenSSL 工具、目标服务 HTTPS 访问权限、CA 证书文件
  • 验收:Prometheus 控制台 Targets 页面显示 UP 且无证书错误

1. 生成与分发证书

使用 OpenSSL 生成自签名证书。生成后,需将公钥证书(.crt)分发到 Prometheus 服务器,私钥(.key)保留在目标服务侧。

openssl req -x509 -newkey rsa:4096 -nodes -keyout prom.key -out prom.crt -days 365 -subj "/CN=target-service"

注意:若目标服务通过 IP 访问,建议在扩展主题(SAN)中包含 IP 地址,否则可能因域名不匹配导致验证失败。

2. 目标服务配置 HTTPS

确保被监控服务已启用 HTTPS 监听。以 Nginx 为例,加载生成的证书配置如下:

server {
    listen 443 ssl;
    server_name target-service;

    ssl_certificate /etc/nginx/ssl/prom.crt;
    ssl_certificate_key /etc/nginx/ssl/prom.key;

    location /metrics {
        # 暴露指标接口
    }
}

配置完成后重启 Nginx 并确认端口监听状态:netstat -tlnp | grep 443

3. Prometheus 抓取配置

编辑 prometheus.yml,根据安全需求选择配置方式。

方式一:配置 CA 证书验证(推荐)

Prometheus 配置 HTTPS 自签名证书抓取目标的具体步骤是什么

将之前生成的 prom.crt 复制到 Prometheus 服务器(如 /etc/prometheus/ca.crt),并在配置中指定:

scrape_configs:
  - job_name: 'https-target-secure'
    scheme: https
    tls_config:
      ca_file: '/etc/prometheus/ca.crt'
    static_configs:
      - targets: ['target-ip:443']

方式二:跳过证书验证(仅限测试/内网)

若无法配置 CA 信任,可禁用验证,但存在中间人攻击风险:

scrape_configs:
  - job_name: 'https-target-insecure'
    scheme: https
    tls_config:
      insecure_skip_verify: true
    static_configs:
      - targets: ['target-ip:443']

4. 验证与排查

配置检查:重载前使用 promtool 检查配置语法:

promtool check config /etc/prometheus/prometheus.yml

重载配置:发送 SIGHUP 信号或调用 reload 接口:

kill -HUP $(pidof prometheus)
# 或
curl -X POST http://localhost:9090/-/reload

状态验收:登录 Prometheus Web 控制台,进入 Status > Targets 页面。查看对应 job 状态,显示 UP 且 Last Error 为空即为成功。

命令行验证:在 Prometheus 服务器上使用 curl 测试连通性:

# 使用 CA 验证
curl `--cacert` /etc/prometheus/ca.crt https://target-ip:443/metrics
# 或跳过验证测试
curl -k https://target-ip:443/metrics

5. 常见坑与风险

  • 证书路径权限:确保 Prometheus 进程用户有权限读取 ca_file 指定的证书文件。
  • SAN 匹配问题:若 targets 使用 IP 地址,证书必须包含该 IP 的 SAN 记录,否则即使配置 ca_file 也会报错。
  • 证书过期:自签名证书通常有效期较短,需设置监控告警关注证书过期时间。
  • 安全风险:insecure_skip_verify 会禁用证书验证,生产环境严禁使用,仅限内网可信环境临时调试。

参考文档