使用 TLS 加密保护 Prometheus API 和 UI 端点的安全
Prometheus 支持传输层安全 (TLS) 协议,用于加密到 Prometheus 实例的连接(即到表达式浏览器或 HTTP API 的连接)。如果您希望强制为这些连接使用 TLS,您需要创建一个特定的 Web 配置文件。
注意本指南是关于连接_到_Prometheus 实例的 TLS 连接。对于_从_Prometheus 实例到抓取目标的连接,也支持 TLS。
前提条件
假设您已经有一个正在运行的 Prometheus 实例,并且想要对其进行调整。本指南不会涵盖 Prometheus 的初始设置。
假设您想运行一个通过 TLS 提供服务的 Prometheus 实例,该实例可在 example.com 域(您拥有该域)下访问。
再假设您已经使用 OpenSSL 或类似工具生成了以下内容:
- 一个位于
/home/prometheus/certs/example.com/example.com.crt的 SSL 证书 - 一个位于
/home/prometheus/certs/example.com/example.com.key的 SSL 密钥
您可以使用以下命令生成自签名证书和私钥:
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