谢晋杰
发布于 2025-08-09 / 4 阅读
0
0

使用Certbot申请Let's Encrypt免费证书

现在用的是Let's Encrypt的证书,现在免费的证书都有有效期,Let's Encrypt的证书可以在服务器配置自动续期。

下载Certbot

Certbot是Let's Encrypt证书的命令行工具。

首先登录服务器,使用系统包管理工具下载Certbot,下面命令是Centos的。

yum install certbot -y

申请证书

申请证书也很简单,比如要申请证书的域名是http://example.com和http://www.example.com,命令如下:

certbot certonly --standalone -d example.com -d www.example.com

这里注意一点,Certbot申请证书,会启动一个认证服务,会用到80端口,有其它服务占用的话会导致申请失败。

申请好的证书位于/etc/letsencrypt/live/目录下。

证书自动续期

自动续期就是配置一个定时任务,定时触发Certbot续期命令

  • Certbot续期命令

certbot renew --pre-hook "docker stop nginx" --post-hook "docker start nginx" --dry-run

有几个参数注意一下:

--pre-hook和--post-hook:申请续期前后执行的命令,因为Certbot会用到80端口,所以申请前停止了nginx服务,申请后再重新启动。我是用的nginx的docker,命令可以按自己实际情况替换。

--dry-run:表示这次申请是一次测试,用来检查能不能正常申请续期。

  • 定时任务配置

使用crontab配置,执行下面命令:

crontab -e

添加下面内容就可以了:

0 2 * * * /usr/bin/certbot renew --pre-hook "docker stop nginx" --post-hook "docker start nginx" --quiet

每天凌晨2点会执行Certbot续期命令,如果证书没有过期,也不会重启服务。

最后加一个查看certbot申请证书状态的命令

certbot certificates


评论