CA 与证书

使用自签名或真实 HTTPS 证书

本文介绍如何使用 Certbot 和 Let’s Encrypt 为 Pigsty 获取和管理 HTTPS 证书。

前置条件

  • 拥有公网域名
  • DNS 记录指向服务器的公网 IP
  • Nginx 已正确配置

配置步骤

第一步:域名配置

infra_portal 中配置需要证书的服务域名(Grafana、VictoriaMetrics、AlertManager、MinIO 等):

infra_portal:
  home: { domain: pigsty.cc }
  grafana: { domain: g.pigsty.cc, endpoint: "${admin_ip}:3000", websocket: true }
  prometheus: { domain: p.pigsty.cc, endpoint: "${admin_ip}:8428" }
  alertmanager: { domain: a.pigsty.cc, endpoint: "${admin_ip}:9059" }

第二步:DNS 配置

通过 A 记录将所有域名指向服务器的公网 IP。使用 nslookupdig 验证:

nslookup g.pigsty.cc
dig +short g.pigsty.cc

第三步:申请证书

交互式方式:

certbot --nginx -d pigsty.cc -d g.pigsty.cc -d p.pigsty.cc -d a.pigsty.cc

非交互式方式:

certbot --nginx --agree-tos --email admin@pigsty.cc -n \
  -d pigsty.cc -d g.pigsty.cc -d p.pigsty.cc -d a.pigsty.cc

第四步:Nginx 配置

在 portal 条目中添加 certbot: true 参数,然后重新生成配置:

./infra.yml -t nginx_config,nginx_launch

第五步:自动续期

测试续期(预演模式):

certbot renew --dry-run

设置 cron 定时任务(每月 1 日凌晨 2 点):

0 2 1 * * certbot renew --quiet

或启用 systemd 定时器:

systemctl enable certbot.timer

管理命令

命令说明
certbot certificates列出所有证书
certbot renew --cert-name domain.com续期指定证书
certbot delete --cert-name domain.com删除证书
certbot revoke --cert-path /path/to/cert.pem吊销证书

故障排查

问题解决方案
域名无法访问验证 DNS 传播是否完成
端口 80 被阻止确保验证时端口 80 开放
请求频率限制避免短时间内多次申请证书
防火墙问题开放 80 和 443 端口

最佳实践

  • 使用通配符证书管理子域名
  • 设置证书过期告警监控
  • 定期测试续期流程
  • 备份证书文件
  • 记录域名配置文档

最后修改 2025-12-20: update some docs to v4.0 (6c231c3)