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

Prometheus 支持传输层安全 (TLS) 加密,用于连接到 Prometheus 实例(即表达式浏览器或 HTTP API)。如果您想为这些连接强制执行 TLS,您需要创建一个特定的 Web 配置文件。

注意: 本指南是关于 *到* Prometheus 实例的 TLS 连接。*从* Prometheus 实例到 抓取目标 的连接也支持 TLS。

先决条件

假设您已经有一个正在运行的 Prometheus 实例,并且您想要对其进行调整。本指南不涵盖 Prometheus 的初始设置。

假设您想要运行一个通过 TLS 提供的 Prometheus 实例,该实例可在 example.com 域(您拥有该域)上访问。

还假设您已使用 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

本文档是开源的。请提交 issue 或 pull request 来帮助改进它。