如何为 Grafana 内置服务器配置自动续期 Let's Encrypt 证书?
解读
面试官问的是“Grafana 内置服务器”,而不是放在 Nginx 后面的场景。国内机房普遍80/443 端口需备案,且 Let's Encrypt 验证节点常被限速或丢包,因此回答必须兼顾:
- 如何在内置服务器上启用 TLS
- 如何自动续期(ACME 协议)
- 如何绕过国内网络抖动与备案限制
- 如何与 Grafana 自身配置 reload 联动,做到零中断
知识点
- Grafana 内置 TLS 开关:
[server]段protocol = https,cert_file,cert_key - 证书格式要求:全链 PEM,RSA ≥2048 bit,兼容 Go crypto/tls
- ACME 客户端选型:
– Lego:纯 Go,支持 DNS-01 挑战,无 80/443 依赖,适合国内未备案主机
– Certbot:功能全,但默认 HTTP-01/TLS-ALPN-01,需开放 80/443,备案风险高 - DNS-01 挑战:在阿里云、腾讯云、华为云等 DNS 厂商均有 OpenAPI,需提前申请 AK/SK 并授予更改解析权限
- 证书热更新:Grafana ≥9.0 支持 SIGHUP 平滑重载;<9.0 需外部脚本
kill -HUP - 续期周期:Let's Encrypt 90 天,官方建议 60 天续期;cron/systemd timer 每天跑一次,剩余 30 天触发续期
- 权限隔离:证书目录
/etc/grafana/certs属主 root:grafana,权限 0640,防私钥泄露 - 告警兜底:Prometheus 外部黑盒 exporter 探测
probe_ssl_earliest_cert_expiry,<21 天触发钉钉/飞书
答案
-
选 DNS-01 挑战,避开备案端口
以阿里云 DNS 为例,创建 RAM 子账号,仅授予AliyunDNSFullAccess,导出ALICLOUD_ACCESS_KEY与ALICLOUD_SECRET_KEY -
安装 lego
curl -sL https://github.com/go-acme/lego/releases/latest/download/lego_linux_amd64 -o /usr/local/bin/lego chmod +x /usr/local/bin/lego -
申请证书
lego --email=your@example.cn \ --dns=alidns \ --domains=grafana.example.cn \ --path=/etc/grafana/certs \ --key-type=ec256 \ run成功后得到
/etc/grafana/certs/certificates/grafana.example.cn.crt与.key -
配置 Grafana
编辑/etc/grafana/grafana.ini:[server] protocol = https http_addr = 0.0.0.0 http_port = 3000 domain = grafana.example.cn cert_file = /etc/grafana/certs/certificates/grafana.example.cn.crt cert_key = /etc/grafana/certificates/grafana.example.cn.key重启 Grafana:
systemctl restart grafana-server -
自动续期脚本
/usr/local/bin/renew-grafana-cert.sh#!/bin/bash export ALICLOUD_ACCESS_KEY=xxx export ALICLOUD_SECRET_KEY=xxx lego --dns=alidns --domains=grafana.example.cn --path=/etc/grafana/certs renew --days 30 if [ $? -eq 0 ]; then # 平滑重载,零中断 kill -HUP $(pidof grafana-server) fi加执行权限,加入 systemd timer 每日 02:30 运行:
[Unit] Description=Renew Grafana LE cert [Timer] OnCalendar=*-*-* 02:30:00 Persistent=true [Install] WantedBy=timers.target -
验证
openssl s_client -connect grafana.example.cn:3000 2>/dev/null | openssl x509 -noout -dates- 手动调 timer:
systemctl start renew-grafana-cert.timer - 查看 Grafana 日志:
"HTTP Server TLS settings" ... "certificates loaded"
拓展思考
- 双证书热备:在 DNS-01 失败时,可预置 自签 CA 证书 作为 fallback,通过 Grafana 反向代理层(如 Envoy)做证书切换,保障监控永远可观测
- 集中式 ACME 网关:若公司已有 cert-manager 集群,可用 CSI 驱动 把证书以 Secret 形式挂到裸机 Grafana,统一审计与轮换
- 国密合规:金融场景需 SM2 证书,Let's Encrypt 不支持,可改用 CFCA 免费测试证书,通过 Tongsuo(原 BabaSSL) 提供国密 TLS 1.3,Grafana 侧用 反向代理卸载,内置服务器仅监听 127.0.0.1
- 审计与回滚:每次续期后把旧证书备份到 S3 兼容对象存储(如阿里云 OSS),保留 3 个周期,方便异常时秒级回滚
- 灰度验证:在 边缘节点 先用 staging 环境域名做 canary 续期,确认 lego 版本与云厂商 API 无 breaking change 后,再推到生产,避免一次性全网证书掉链