跳到主要内容
Apache

certbot 自动申请与续期 Let’s Encrypt 证书:从签发到无人值守的完整实践

问题背景与根因:90 天证书为什么总会“意外”过期

Let’s Encrypt 签发的 DV 证书有效期固定为 90 天,官方推荐在剩余 30 天左右完成续期,也就是每 60 天左右必须成功执行一次 ACME 流程。与此同时,公有 CA 证书的最长有效期受 CA/B Forum 基线要求与浏览器厂商策略双重约束,自 2020 年 9 月起上限为 398 天;SC-081 提案通过后,这一上限将在 2026-03-15 降至 200 天、2027-03-15 降至 100 天、2029-03-15 降至 47 天。这意味着“一年一续、到期前手工换证书”的运维模式已经彻底失效,任何依赖人工记忆的流程都会在某个凌晨变成线上事故。

certbot 的价值在于把 ACME(RFC 8555)的账号注册、订单创建、挑战应答、CSR 提交、证书下载、配置重载全流程脚本化,并交给 systemd timer 或 cron 周期触发。但“装了 certbot 就万事大吉”是最大的误解——自动续期失败往往静默发生,直到浏览器弹出 NET::ERR_CERT_DATE_INVALID 才被发现。

常见根因可以归为六类:

  • 验证通道被破坏:安全组、防火墙、WAF 或 CDN 拦截了 80 端口的 /.well-known/acme-challenge/ 路径,或者 nginx 只监听 IPv6 而 CA 从 IPv4 回源。
  • webroot 路径失效:容器重建后 /var/www/html 被清空,或目录权限不足导致 nginx 返回 403。
  • DNS-01 记录残留:上一次挑战的 TXT 记录未清理,CA 查询到多条冲突记录判定失败。
  • 服务器时钟漂移:时间偏差超过 5 分钟,JWS 签名被 CA 拒绝,报 JWS has an invalid anti-replay nonce 或 Request time is too far in the future。
  • 配置被人工覆盖:有人手工改过 nginx 站点文件,但 /etc/letsencrypt/renewal/ 里的认证器参数没同步,续期时找不到对应 server 块。
  • 速率限制:反复调试触发 too many failed authorizations recently,账号被锁定 1 小时。

下面按“安装 → 签发 → 自动续期 → 配置固化 → 排错 → 验证”的顺序给出可直接执行的完整流程,命令在 Debian 12 / Ubuntu 22.04 与 nginx 1.24 环境下验证通过。

环境准备与 certbot 安装:apt、snap 与 pip 的取舍

先确认基础条件。域名 A/AAAA 记录必须已指向本机,且 80 端口对公网可达(HTTP-01 验证必需);服务器时间必须准确:

timedatectl status
# 若输出 System clock synchronized: no,执行:
apt install -y systemd-timesyncd && timedatectl set-ntp true
dig +short example.com A
dig +short example.com AAAA
curl -I http://example.com/.well-known/acme-challenge/test

安装方式有三种,差异很大:

  • 发行版仓库(apt):最省事,一条命令装好插件,但版本通常落后主版本若干个小版本,某些新参数(如 --preferred-profile、ECDSA 默认密钥)可能不支持。Debian/Ubuntu 下执行:apt update && apt install -y certbot python3-certbot-nginx。
  • snap:官方推荐渠道,版本最新,自带自动更新。执行 snap install --classic certbot,再 ln -s /snap/bin/certbot /usr/bin/certbot。注意国内网络拉取 snap 较慢,可先配置镜像或改用 pip。
  • pip:适合需要 DNS 插件(如 certbot-dns-cloudflare)的场景,用 venv 隔离避免污染系统 Python。

安装后必须核对版本与插件是否加载成功,否则后续命令会报 The requested nginx plugin does not appear to be installed:

certbot --version
# certbot 4.x.x
certbot plugins --text
# 列表中应出现 nginx / standalone / webroot
nginx -v
systemctl is-active nginx

若使用 apt 安装但插件未加载,通常是因为 python3-certbot-nginx 装到了另一个 Python 解释器下,可用 apt install --reinstall python3-certbot-nginx 修复,或直接切到 snap 版本。

签发证书:–nginx 与 certonly –webroot 两种模式

第一次签发建议先跑一次 staging 演练,避免消耗生产配额(生产环境同一注册域名每周限额 50 张,重复失败还会触发 too many failed authorizations):

certbot --nginx -d example.com -d www.example.com 
  --agree-tos -m ops@example.com --redirect --staging
# 演练通过后去掉 --staging 正式签发
certbot --nginx -d example.com -d www.example.com 
  --agree-tos -m ops@example.com --redirect

--nginx 是“认证器 + 安装器”一体模式:certbot 会临时改写 nginx 配置注入 challenge location,验证成功后自动写回 443 server 块、补 ssl_certificate 与 ssl_certificate_key,并按 --redirect 增加 301 跳转。优点是零手工;缺点是会改动你的配置文件(生成 # managed by Certbot 注释块),如果站点配置由 Ansible/容器镜像管理,下次下发会覆盖掉这些改动。

这类环境应改用 webroot 模式,只申请证书不碰 nginx:

mkdir -p /var/www/html/.well-known/acme-challenge
chown -R www-data:www-data /var/www/html
certbot certonly --webroot -w /var/www/html 
  -d example.com -d www.example.com 
  --agree-tos -m ops@example.com --keep-until-expiring

对应的 nginx 片段(放在 80 端口的 server 块内):

location ^~ /.well-known/acme-challenge/ {
    root /var/www/html;
    default_type text/plain;
    try_files $uri =404;
}

需要通配符证书(*.example.com)时,HTTP-01 无法完成验证,必须走 DNS-01。此时 --nginx 会直接报错 Client with the currently selected authenticator does not support any combination of challenges that will satisfy the CA。以 Cloudflare 为例:

pip install certbot-dns-cloudflare
cat > /root/.secrets/cloudflare.ini <<'EOF'
dns_cloudflare_api_token = YOUR_SCOPED_TOKEN
EOF
chmod 600 /root/.secrets/cloudflare.ini
certbot certonly --dns-cloudflare 
  --dns-cloudflare-credentials /root/.secrets/cloudflare.ini 
  --dns-cloudflare-propagation-seconds 30 
  -d example.com -d '*.example.com' --agree-tos -m ops@example.com

自动续期机制:systemd timer、cron 与 deploy-hook

apt 与 snap 安装的 certbot 都会自带 systemd timer,无需手工写 cron。验证方式:

systemctl list-timers certbot.timer
systemctl status certbot.timer --no-pager
cat /lib/systemd/system/certbot.timer

timer 默认每天触发两次(带随机延迟,避免整点冲击 CA),实际执行的是 certbot renew。renew 会遍历 /etc/letsencrypt/renewal/*.conf,只对“剩余有效期小于 renew_before_expiry”的证书动作,其余输出 Certificate not yet due for renewal 并跳过——这是正常现象,不是失败。

关键一步是部署钩子:证书文件更新后,nginx 不会自动重新加载,仍在使用旧证书,直到有人 reload。必须在 renewal 配置或命令行中挂上 hook:

# 方式一:写进 renewal 配置(推荐,持久生效)
# /etc/letsencrypt/renewal/example.com.conf 末尾追加:
# renew_hook = systemctl reload nginx

# 方式二:签发时直接指定
certbot --nginx -d example.com --deploy-hook 'systemctl reload nginx'

没有 systemd 的旧系统(CentOS 7、Alpine 容器)可用 cron 替代,注意加随机延迟并显式指定日志:

echo '17 3,15 * * * root /usr/bin/certbot renew --quiet --deploy-hook "systemctl reload nginx"' 
  > /etc/cron.d/certbot
systemctl restart crond

容器化部署时更稳妥的做法是把证书目录挂载出来(-v /etc/letsencrypt:/etc/letsencrypt),由宿主机上的 certbot 统一续期,容器内只读挂载,避免多个实例并发续期导致文件写坏。

配置示例:Nginx TLS 参数与 renewal 配置文件

证书签发完成后,建议把 nginx 的 TLS 参数固化下来,而不是依赖 certbot 生成的默认值。以下为 nginx 1.24 上兼顾兼容性与安全性的配置:

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;
    server_name example.com www.example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
}

注意两点修正:其一,不要再配 ssl_stapling on。Let’s Encrypt 已于 2025 年 5 月停止提供 OCSP 响应并转向 CRL,对 LE 证书开启 stapling 只会让 nginx 反复拉取失败、日志刷 ssl_stapling ignored, issuer certificate not found,直接删掉即可。其二,ssl_certificate 必须指向 fullchain.pem 而非 cert.pem,否则部分 Android 与 Java 客户端会报 unable to get local issuer certificate。

renewal 配置文件决定续期行为,签发后会自动生成,可按需调整:

# /etc/letsencrypt/renewal/example.com.conf
[renewalparams]
authenticator = webroot
webroot_path = /var/www/html,
installer = nginx
server = https://acme-v02.api.letsencrypt.org/directory
key_type = ecdsa
renew_before_expiry = 30 days
renew_hook = systemctl reload nginx

全局默认值可写在 /etc/letsencrypt/cli.ini,避免每次敲一长串参数:

# /etc/letsencrypt/cli.ini
email = ops@example.com
agree-tos = true
key-type = ecdsa
elliptic-curve = secp256r1
max-log-backups = 20
preferred-chain = "ISRG Root X1"

验证方式与工具选型对比

选错验证方式是续期失败的头号原因,下表按端口、通配符支持与适用场景做横向对比:

验证方式 依赖端口 通配符 是否需停机 典型适用场景
HTTP-01 80/tcp 不支持 否 普通站点、webroot 模式、有公网 80 端口
DNS-01 无(仅需出网 53) 支持 否 通配符证书、80 端口被封、内网机器、CDN 回源
TLS-ALPN-01 443/tcp 不支持 否 80 被封但 443 可用、无 web 服务的纯 TLS 服务

工具层面,certbot 并非唯一选择。国内 DNS 解析商(阿里云、DNSPod、华为云)的 API 在 acme.sh 中支持更完整,且 acme.sh 是纯 shell、无 Python 依赖,在 Alpine 与精简镜像里更轻:

维度 certbot acme.sh lego
运行时依赖 Python 3 POSIX shell + curl Go 静态二进制
自动续期 systemd timer / cron 安装时写入 crontab 需自建定时任务
DNS API 覆盖 插件式,需逐个 pip 安装 内置 150+ 服务商 内置主流服务商
nginx 自动改配置 支持(–nginx) 不支持,需手工配置 不支持
国内可用性 一般 好 好

结论:有公网 80 端口、需要 certbot 自动改 nginx 配置的,用 certbot;需要通配符、走国内 DNS 商 API、或环境无 Python 的,用 acme.sh 更稳。acme.sh 的典型命令为 acme.sh --issue --dns dns_dp -d example.com -d '*.example.com',续期由安装时写入的 crontab 每日检查。

常见错误排查:从真实报错到定位路径

所有 ACME 交互细节都记录在 /var/log/letsencrypt/letsencrypt.log,排错第一步永远是看这个文件的最新一段(tail -n 200),并且用 --debug-challenges 暂停挑战过程便于人工验证。以下是最常遇到的六类报错:

# 1) 80 端口被占用
Problem binding to port 80: Could not bind to IPv4 or IPv6.
# 定位:ss -lntp | grep :80,停掉占用进程,或改用 --webroot / DNS-01

# 2) 挑战文件内容不匹配(多为多实例负载不均或缓存)
The key authorization file from the server did not match this challenge
# 排查:curl -v http://example.com/.well-known/acme-challenge/<token>

# 3) 验证请求超时
Timeout during connect (likely firewall problem)
# 排查:安全组、云厂商 WAF、CDN 回源是否放行 80;IPv6 AAAA 记录是否指向错误主机

# 4) 速率限制
too many failed authorizations recently
# 处理:等待 1 小时,期间用 --staging 调试

# 5) 通配符用错认证器
Client with the currently selected authenticator does not support any combination of challenges
# 处理:改用 --dns-* 插件

# 6) 证书已更新但浏览器仍显示旧证书
nginx: [emerg] cannot load certificate "/etc/letsencrypt/live/example.com/fullchain.pem"
# 原因多为符号链接指向的 archive 目录被清理,或 SELinux 拒绝读取
# 排查:ls -l /etc/letsencrypt/live/example.com/;ausearch -m avc -ts recent

还有一个高频但不算报错的场景:certbot renew --dry-run 报 Failed to renew certificate example.com with error: The server could not connect to the client to verify the domain,而生产续期其实是好的——因为 dry-run 走 staging 环境,若你在 nginx 里对 staging 的 UA 做了拦截,就会误判。此时先看 letsencrypt.log 中的 challenge URL 是否可访问,再决定是否修改。

另外建议开启失败通知,certbot 支持 --deploy-hook 与邮件,但更可靠的是把续期结果接入监控:解析 certbot certificates 的到期时间并在剩余 21 天时告警。

效果验证:从 openssl 到到期监控

签发和续期完成后,必须做四层验证,缺一层都可能留下隐患。

第一层:本地证书列表。确认路径、域名覆盖范围与到期时间:

certbot certificates
# Certificate Name: example.com
#   Domains: example.com www.example.com
#   Expiry Date: 2026-05-18 03:12:44+00:00 (VALID: 89 days)
#   Certificate Path: /etc/letsencrypt/live/example.com/fullchain.pem

第二层:线上实际返回的证书。本地文件对不代表 nginx 已加载,必须从外部视角确认:

openssl s_client -connect example.com:443 -servername example.com < /dev/null 2>/dev/null 
  | openssl x509 -noout -subject -issuer -dates -ext subjectAltName
curl -sI https://example.com | head -n 3
# 期望看到 HTTP/2 200 或 301

重点核对三项:notAfter 是否是刚续期后的新日期;subjectAltName 是否同时包含 apex 与 www;issuer 是否为 C = US, O = Let's Encrypt, CN = R11 之类的中间 CA 而非 staging 的 (STAGING) Pretend Pear。

第三层:协议与链完整性。用 openssl s_client -connect example.com:443 -tls1_2 与 -tls1_3 分别握手,确认没有 verify error:num=21:unable to verify the first certificate;再检查是否误用了 cert.pem 导致缺中间证书。

第四层:续期演练与到期监控。每季度执行一次 dry-run,并确认 timer 正常工作:

certbot renew --dry-run --cert-name example.com
systemctl list-timers certbot.timer --no-pager
grep -c 'renew' /var/log/letsencrypt/letsencrypt.log

最后把到期时间接入监控,最简版本用 shell + 告警:

END=$(openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null 
  | openssl x509 -noout -enddate | cut -d= -f2)
DAYS=$(( ( $(date -d "$END" +%s) - $(date +%s) ) / 86400 ))
[ "$DAYS" -lt 21 ] && echo "CERT EXPIRING in $DAYS days" | mail -s "TLS ALERT" ops@example.com

完成以上四层验证,才算真正做到“签发一次、无人值守、过期前必有告警”。

常见问题

不会。dry-run 会自动切换到 staging 环境(acme-staging-v02)签发测试证书,不占用生产配额。但 staging 也有独立的速率限制,反复失败同样会被临时锁定,因此调试时建议配合 –debug-challenges 一次定位问题。

不是失败,是正常的跳过逻辑。certbot 默认只在剩余有效期小于 30 天时才真正续期,对应 renewal 配置里的 renew_before_expiry = 30 days。如果想提前续,可调大该值或用 certbot renew –force-renewal 强制,但不建议频繁强制续期。

两种方案:一是改用 DNS-01 验证(–dns-cloudflare 插件),完全绕开回源端口;二是在 CDN 侧放行 /.well-known/acme-challenge/ 路径并确保回源到正确的后端。若 CDN 开启强制 HTTPS 或 WAF 拦截,也要为该路径加白名单。

不能。通配符域名只支持 DNS-01 验证,使用 –nginx 会直接报 Client with the currently selected authenticator does not support any combination of challenges that will satisfy the CA。必须改用 –dns-cloudflare、–dns-aliyun 等 DNS 插件,或换用 acme.sh。

可以。改用 DNS-01 验证即可,全程不需要 80 或 443 入站;若 443 可用,也可用 TLS-ALPN-01。注意此时不能使用 –nginx 或 –webroot,必须配置对应的 DNS 插件并保证 API Token 有修改 TXT 记录的权限。

先确认 nginx 是否已 reload:没有 –deploy-hook 时 certbot 只写文件不重载进程。执行 nginx -t && systemctl reload nginx 后,再用 openssl s_client 从外部核对 notAfter。若仍不对,检查是否有 CDN 缓存或前置负载均衡仍持有旧证书。

内容审核

长期从事 SSL/TLS 证书部署与 HTTPS 运维,负责本站证书选型、安装配置与故障排查内容的编写与审核。