请参与 Prometheus 用户调研(2026 年 3 月版) ,帮助社区确定未来开发工作的优先级!

使用 TLS 加密保护 Prometheus API 和 UI 端点

Prometheus 支持 传输层安全协议 (TLS)  加密,用于连接 Prometheus 实例(例如连接到表达式浏览器或 HTTP API)。如果你希望强制这些连接使用 TLS,则需要创建一个特定的 Web 配置文件。

注意本指南介绍的是连接到 Prometheus 实例的 TLS。Prometheus 同时也支持从 Prometheus 实例连接到 抓取目标 的 TLS 加密。

先决条件

假设你已经运行了一个 Prometheus 实例,并希望对其进行适配。本指南不涉及 Prometheus 的初始设置。

假设你想要运行一个使用 TLS 服务且可在 example.com 域名(你所拥有的)下访问的 Prometheus 实例。

同时也假设你已经使用 OpenSSL  或类似工具生成了以下内容:

  • SSL 证书位于 /home/prometheus/certs/example.com/example.com.crt
  • SSL 密钥位于 /home/prometheus/certs/example.com/example.com.key

你可以使用此命令生成自签名证书和私钥:

mkdir -p /home/prometheus/certs/example.com && cd /home/prometheus/certs/certs/example.com
openssl req \
  -x509 \
  -newkey rsa:4096 \
  -nodes \
  -keyout example.com.key \
  -out example.com.crt

在提示符处填写相应的信息,并确保在 Common Name 提示符下输入 example.com

Prometheus 配置

以下是一个示例 web-config.yml 配置文件。使用此配置,Prometheus 将通过 TLS 服务其所有端点。

tls_server_config:
  cert_file: /home/prometheus/certs/example.com/example.com.crt
  key_file: /home/prometheus/certs/example.com/example.com.key

要使 Prometheus 使用此配置,你需要通过 --web.config.file 标志来启动它。

prometheus \
  --config.file=/path/to/prometheus.yml \
  --web.config.file=/path/to/web-config.yml \
  --web.external-url=https://example.com/

--web.external-url= 标志在此处是可选的。

测试

如果你想使用 example.com 域名在本地测试 TLS,可以在 /etc/hosts 文件中添加一条记录,将 example.com 重定向到 localhost

127.0.0.1     example.com

然后,你可以使用 cURL 与本地的 Prometheus 设置进行交互。

curl --cacert /home/prometheus/certs/example.com/example.com.crt \
  https://example.com/api/v1/label/job/values

你可以使用 --insecure-k 标志连接到 Prometheus 服务器,而无需指定证书。

curl -k https://example.com/api/v1/label/job/values

本页内容