概述
谷歌证书(通过Let's Encrypt服务颁发)的有效期通常为90天。为了确保网站或应用程序始终受到保护,需要定期续订证书。Certbot提供了自动化续订功能,可以通过配置cron作业或systemd服务来实现定期续订。
使用Certbot续订证书
Certbot在安装时会设置一个续订脚本,该脚本负责在证书即将到期时自动续订。默认情况下,续订的证书会保存在与原始证书相同的目录中。
配置cron作业实现自动化续订
- 编辑crontab文件
使用crontab -e命令打开当前用户的crontab编辑界面。
- 添加续订任务
在crontab文件中添加以下行,以每天检查并续订证书(建议根据实际需求调整频率):
0 0 * * * /usr/bin/certbot renew --quiet --no-self-upgrade && /usr/bin/systemctl reload nginx
这行命令的含义是:每天午夜0点,执行Certbot的续订命令,并在续订成功后重新加载Nginx服务(或其他你正在使用的Web服务器)。
- 保存并退出
编辑完成后,保存并退出crontab编辑器。
配置systemd服务实现自动化续订
- 创建systemd服务单元文件
在/etc/systemd/system/目录下创建一个新的服务单元文件,例如certbot-renew.service:
[Unit]
Description=Certbot renew certificates
[Service]
Type=oneshot
ExecStart=/usr/bin/certbot renew --quiet --no-self-upgrade
ExecReload=/usr/bin/systemctl reload nginx # 根据你使用的Web服务器进行调整
[Install]
WantedBy=multi-user.target
- 启用并启动服务
使用以下命令启用并启动该服务:
sudo systemctl enable certbot-renew.service
sudo systemctl start certbot-renew.service
- 设置定时器
创建一个定时器,以便定期运行上述服务:
sudo systemctl edit --full certbot-renew.timer
在打开的编辑器中,输入以下内容:
[Unit]
Description=Run certbot-renew daily
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
保存并退出编辑器后,启用并启动定时器:
sudo systemctl enable certbot-renew.timer
sudo systemctl start certbot-renew.timer
验证自动化续订
- 检查cron作业或systemd服务的状态
使用crontab -l
查看cron作业列表,或使用systemctl status certbot-renew.timer
查看systemd定时器的状态。
- 手动触发续订并观察结果
可以手动运行续订命令(如/usr/bin/certbot renew --dry-run
)来模拟续订过程,并观察是否有任何错误或警告信息。
- 监控证书有效期
定期检查证书的有效期,确保自动化续订过程正常工作。可以使用certbot certificates命令查看当前已安装的证书及其到期日期。