Prometheus 抓取时如何添加自定义 HTTP 头?
Prometheus 抓取配置通过 authorization、bearer_token_file 或 oauth2 支持认证头;任意自定义 Header 需借助 version 2.27+ 的 http_headers 字段或反向代理注入。本文给出完整配置示例与安全建议。
Prometheus 2.26.0+ 支持在 scrape_config 中用 authorization 设置 Authorization 头;任意自定义 HTTP 头则用 http_headers 字段(2.55.0+),老版本只能借助反向代理注入。
认证头:Authorization / Bearer Token
scrape_configs:
- job_name: 'secure-app'
scheme: https
static_configs:
- targets: ['app:9090']
authorization:
type: Bearer
credentials_file: /etc/prometheus/token
也可以用 basic_auth(username/password)或 oauth2 客户端凭证模式。
任意自定义头:http_headers
scrape_configs:
- job_name: 'custom-headers'
static_configs:
- targets: ['app:9090']
http_headers:
X-Scope-OrgID:
values: ['team-a']
X-Custom-Header:
values: ['my-value']
注意:http_headers 不能覆盖 Prometheus 自身设置的保留头;认证优先使用 authorization/basic_auth/oauth2 字段。敏感自定义头按所用版本使用 secrets/files,普通 values 不会自动按秘密处理。
老版本的替代方案:反向代理
在目标前架一个 Nginx/Traefik 代理,由代理统一注入请求头,Prometheus 抓代理地址即可。
常见问题(FAQ)
Q:Token 写在配置文件里安全吗? 用 credentials_file 引用文件并收紧文件权限,不要把密钥提交进 Git。
Q:每个 target 能用不同的头吗? http_headers 是 job 级配置;不同头请拆 job。
Q:抓取报 401 怎么排查? 先用 curl 带同样的头手动请求 /metrics 验证凭据有效性。