Nginx需借助cert-exporter暴露证书过期时间戳,Prometheus抓取后用PromQL计算剩余天数,再通过Alertmanager对≤7天过期证书告警。

Nginx 本身不提供证书过期监控能力,必须借助外部工具将证书有效期转化为 Prometheus 可采集的指标,再通过 PromQL 计算剩余天数、配置告警规则。整个流程分三步:暴露指标、抓取数据、触发告警。
用 cert-exporter 暴露证书过期时间戳
cert-exporter 是专为 TLS 证书设计的轻量 Exporter,支持本地文件和远程域名两种模式:
- 监控本地 PEM 文件(适合 Let's Encrypt 等自动续签场景):
docker run -d --name cert-exporter -p 9250:9250 \
-e CERT_EXPORTER_CERTIFICATES="/etc/nginx/ssl/example.com.pem" \
-e CERT_EXPORTER_WEB_LISTEN_ADDRESS=":9250" \
quay.io/ricoberger/cert-exporter - 监控线上 HTTPS 端口(更真实反映生产环境):
-e CERT_EXPORTER_CERTIFICATES="https://example.com" - 启动后访问 http://IP:9250/metrics,应看到类似指标:
ssl_cert_not_after_seconds{host="example.com",port="443"} 1748234567
这个值是证书过期时刻的 Unix 时间戳。
Prometheus 抓取并计算剩余天数
在 prometheus.yml 中添加 job:
- 静态配置目标:
- job_name: 'cert-exporter'
static_configs:
- targets: ['192.168.1.100:9250'] - 重启 Prometheus,在 /targets 页面确认状态为 UP;
- 在 Prometheus 表达式浏览器中验证:
ceil((ssl_cert_not_after_seconds - time()) / 86400)
输出即为当前剩余天数(整数),例如 27 表示还有 27 天过期。
配置临期告警并接入 Alertmanager
在 alert.rules.yml 中定义规则:
- 设置阈值(如 ≤ 7 天触发):
- 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" - 确保 Alertmanager 已配置邮件、企业微信或钉钉 Webhook;
- 告警会携带主机名、剩余天数等上下文,便于快速定位问题域名。
不需要修改 Nginx 配置,也不依赖 stub_status 或 reload 操作。只要 cert-exporter 能读到证书或连上 443 端口,整个链路就可稳定运行。


















