certbot renew 实现证书到期自动续费
复制问题

使用 certbot renew
实现证书自动续期
Let’s Encrypt 证书有效期只有90天,因此设置自动续期机制非常重要。下面是完整设置证书自动续期的指南:
手动测试续期
首先,推荐测试续期命令是否正常工作:
sudo certbot renew --dry-run
这个命令会模拟续期过程,但不会实际修改任何证书。确认输出没有错误信息。
设置自动续期
Certbot 在安装时通常会自动添加续期计划任务。以下是检查和设置的方法:
1. 检查现有的续期计划任务
# 对于使用 systemd 的系统
systemctl list-timers | grep certbot
# 对于使用 cron 的系统
sudo ls -la /etc/cron.d/ | grep certbot
2. 检查 Certbot 续期配置
sudo cat /etc/letsencrypt/renewal/code.atalk-ai.com.conf
确保配置文件中包含正确的域名和验证方法。
3. 设置自动续期(如果尚未设置)
方法一:使用 systemd timer(现代 Linux 系统推荐)
-
创建 systemd 服务文件
sudo nano /etc/systemd/system/certbot-renewal.service
添加以下内容:
[Unit] Description=Certbot Renewal [Service] ExecStart=/usr/bin/certbot renew --quiet --nginx
-
创建 systemd 定时器文件
sudo nano /etc/systemd/system/certbot-renewal.timer
添加以下内容:
[Unit] Description=Twice daily renewal of Let's Encrypt certificates [Timer] OnCalendar=*-*-* 00,12:00:00 RandomizedDelaySec=43200 Persistent=true [Install] WantedBy=timers.target
-
启用定时器
sudo systemctl daemon-reload sudo systemctl enable certbot-renewal.timer sudo systemctl start certbot-renewal.timer
-
验证定时器已启用
sudo systemctl list-timers | grep certbot
方法二:使用 cron(适用于所有 Linux 系统)
sudo crontab -e
添加以下行:
0 */12 * * * /usr/bin/certbot renew --quiet --nginx
这会设置每12小时运行一次续期命令。
续期后的自动操作(可选)
如果您需要在证书续期后执行某些操作(如重新加载服务),可以使用 --deploy-hook
参数:
创建续期钩子脚本
sudo nano /etc/letsencrypt/renewal-hooks/deploy/reload-services.sh
添加以下内容:
#!/bin/bash
# 重新加载 Nginx 配置
systemctl reload nginx
设置执行权限:
sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/reload-services.sh
验证自动续期设置
您可以通过以下方式验证自动续期设置:
# 检查下次运行的计划任务时间(systemd)
systemctl list-timers | grep certbot
# 检查 cron 任务
sudo crontab -l | grep certbot
# 检查续期钩子
ls -la /etc/letsencrypt/renewal-hooks/deploy/
监控续期状态
设置续期日志通知(可选):
sudo nano /etc/letsencrypt/renewal-hooks/post/email-notification.sh
添加以下内容(需要安装 mail
命令):
#!/bin/bash
echo "Let's Encrypt certificate renewal completed on $(hostname) at $(date)" | mail -s "Certificate Renewal Status" your-email@example.com
设置权限:
sudo chmod +x /etc/letsencrypt/renewal-hooks/post/email-notification.sh
常见问题排查
如果自动续期不工作,请检查:
-
确认 certbot 命令可以手动运行:
sudo certbot renew --dry-run
-
检查日志文件:
sudo cat /var/log/letsencrypt/letsencrypt.log
-
检查 cron 或 systemd 日志:
# 对于 systemd sudo journalctl -u certbot-renewal # 对于 cron sudo grep CRON /var/log/syslog
-
确保服务器在续期时间允许外部访问端口 80 和 443。
通过以上设置,您的 Let’s Encrypt 证书将会在到期前自动续期,确保您的网站始终保持 HTTPS 可用状态。
重新生成
语音播放
复制回答