直接用 prometheus 抓取 nginx ssl 证书剩余天数并告警,需通过 cert-exporter 暴露 ssl_cert_not_after_seconds 指标,prometheus 抓取后用 promql 计算 ceil((ssl_cert_not_after_seconds - time()) / 86400) 得剩余天数,再配置告警规则(如 ≤7 天)并由 alertmanager 发送通知。

直接用 Prometheus 抓取 Nginx SSL 证书剩余天数并告警,核心在于:让证书信息变成 Prometheus 能识别的指标(即暴露为 /metrics 格式),再通过 PromQL 判断临期,最后配置 Alertmanager 发送告警。
一、获取证书剩余天数并暴露为 Prometheus 指标
不能直接从 Nginx 进程读取证书有效期(Nginx 不提供原生指标),需借助外部工具定期检查证书文件或远程端口,并将结果转成文本格式供 Prometheus 抓取。推荐使用 Blackbox Exporter + 自定义 probe 或更轻量的 cert-exporter。
-
方案 A(推荐):用 cert-exporter
它专为监控 TLS 证书设计,支持本地文件、域名+端口两种模式。例如监控example.com:443:
docker run -d --name cert-exporter -p 9250:9250 -e CERT_EXPORTER_WEB_LISTEN_ADDRESS=":9250" -e CERT_EXPORTER_CERTIFICATES="https://example.com" quay.io/ricoberger/cert-exporter
Prometheus 抓取 http://<cert-exporter-ip>:9250/metrics</cert-exporter-ip> 后,会得到类似指标:ssl_cert_not_after_seconds{host="example.com",port="443"} 1748234567
该时间戳是证书过期时间(Unix 时间),用 PromQL 可算出剩余天数:
ceil((ssl_cert_not_after_seconds{job="cert-exporter"} - time()) / 86400)
二、在 Prometheus 中配置抓取任务
编辑 prometheus.yml,添加 job:
- job_name: 'cert-exporter'
static_configs:
- targets: ['
重启 Prometheus,确认目标页(/targets)中该 job 状态为 UP,且指标 ssl_cert_not_after_seconds 可查。
三、配置临期告警规则
在 Prometheus 的 alert.rules.yml 中添加规则,例如:剩余 ≤ 7 天时触发告警:
groups:
- name: ssl-certificate-alerts
rules:
- alert: SSLCertificateExpiringSoon
expr: ceil((ssl_cert_not_after_seconds - time()) / 86400) for: 2h
labels:
severity: warning
annotations:
summary: "SSL certificate for {{ $labels.host }} expires in {{ $value | printf \"%.0f\" }} days"
注意:for: 2h 避免短暂波动误报;若需更早预警(如 30 天),直接改数字即可。
四、对接 Alertmanager 发送通知
确保 Alertmanager 已配置邮件、企业微信或钉钉等接收渠道。Prometheus 告警触发后,会自动转发到 Alertmanager。示例邮件模板中可直接引用 {{ $labels.host }} 和 {{ $value }},清晰标明哪个域名证书即将过期。
验证方式:临时把告警阈值设为 1000 天,看是否能收到测试告警;或用已知快过期的测试域名验证全流程。











