Ubuntu 20.04 安装 Certbot 后默认会配置自动续签任务,无需手动写 cron,重点在于确认定时器状态和测试续签命令。
先说结论:系统自带机制已足够,无需额外脚本,但必须手动验证一次续签流程
- 适合:使用 Let's Encrypt 免费证书且 Web 服务器暴露在公网的场景
- 先准备:确保 80 或 443 端口可被外部访问,域名解析正确
- 验收:执行 dry-run 测试并通过定时器状态检查
命令速用版
sudo apt update
sudo apt install certbot python3-certbot-nginx
sudo certbot renew `--dry-run`为什么会这样
Let's Encrypt 颁发的证书有效期固定为 90 天,到期必须更换。Certbot 在 Ubuntu 20.04 上安装后,会自动注册一个 systemd 定时器(certbot.timer),每天运行一次检查,发现证书剩余有效期少于 30 天时自动执行续签。
分步处理
1. 安装 Certbot 及插件
sudo apt update
sudo apt install certbot python3-certbot-nginx2. 获取初始证书(如果已有可跳过)
sudo certbot `--nginx` -d yourdomain.com3. 确认定时器已激活
systemctl status certbot.timer4. 配置部署钩子(关键步骤)
确保证书更新后服务自动重载,避免使用旧证书。编辑续签配置或直接在命令中添加:
sudo certbot renew `--deploy-hook` "systemctl reload nginx"若需永久配置,可修改 /etc/letsencrypt/renewal-hooks/deploy/ 下的脚本。
5. 模拟续签测试
sudo certbot renew `--dry-run`怎么验证是否生效
查看证书列表和过期时间:
sudo certbot certificates检查 systemd 定时器下次运行时间:
systemctl list-timers | grep certbot如果 dry-run 显示"Congratulations, all renewals succeeded",则自动续签配置正常。
故障排查与日志
如果续签失败,首先查看 Certbot 详细日志:
sudo tail -f /var/log/letsencrypt/letsencrypt.log如需强制手动更新(用于测试或紧急更换):
sudo certbot renew `--force-renewal`常见错误代码及含义:
- Failed authorization procedure:域名解析未生效或 80 端口被防火墙拦截。
- Hook command failed:部署钩子命令执行错误,检查 Nginx/Apache 配置语法。
常见坑
1. Web 服务器配置未重载:续签成功后,Certbot 会尝试重载 Nginx/Apache,如果配置文件有语法错误,会导致续签后服务不可用。建议配置 `--deploy-hook` 显式重载。
2. 防火墙拦截:确保证书颁发机构能访问 80 端口(HTTP-01 验证)或 443 端口(TLS-ALPN-01 验证)。
3. 频率限制:短时间内多次失败续签会触发 Let's Encrypt 速率限制,建议先用 `--dry-run` 测试。
参考来源
- Certbot Official Instructions - https://certbot.eff.org/instructions
- Let's Encrypt Certificate Lifetime - https://letsencrypt.org/docs/