Docker+certbot+Nginx实现自动续期https证书
使用 Docker 和 Certbot 配置 HTTPS 的完整指南,并自动续期 https 证书。
下载 Certbot 镜像
1 | docker pull certbot/certbot |
创建 docker-compose.yml 文件
1 | mkdir certbot |
docker-compose.yml 配置如下:
1 | # version '3' |
创建 nginx.conf 文件
1 | vim /root/nginx/conf/conf.d/default.conf |
域名验证,配置如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15server {
listen 80;
server_name xxx.com; # 替换为你的域名
#配置http验证可访问
location ^~ /.well-known/acme-challenge/ {
#此目录都是nginx容器内的目录,对应宿主机volumes中的http验证目录,
#而宿主机的又与certbot容器中命令--webroot-path指定目录一致,
#从而就整个串起来了,解决了http验证问题
root /etc/letsencrypt;
}
# 其他请求重定向到HTTPS
location / {
rewrite ^(.*)$ https://$host$1 permanent;
}
}
启动 docker-compose服务
1 | docker compose up -d |
测试证书发放
运行以下命令测试证书发放是否正常:1
docker-compose run --rm certbot certonly --webroot --webroot-path /etc/letsencrypt --dry-run -d xxx.com
如果输出 The dry run was successful.,说明测试成功。
正式获取证书
如果测试成功,去掉 --dry-run 参数正式获取证书:1
docker-compose run --rm certbot certonly --webroot --webroot-path /etc/letsencrypt -d xxx.com
按照提示输入邮箱等信息,完成证书申请。
生成结果文件
Certbot 会在 /root/certbot/certs/live/xxx.com/ 目录下生成证书文件,包括:
fullchain.pem:完整的证书链privkey.pem:私钥
创建 HTTPS 配置文件
1 | server { |
重启 Nginx
重新加载 Nginx 配置以应用 HTTPS:1
docker-compose restart nginx
配置定时任务自动续期
选择 vim 编辑器:1
2select-editor
# 使用 vim.tiny
表达式所在的目录:
/etc/crontab系统定时任务,一般不推荐修改/var/spool/cron/crontabs/目录下,各个用户名下面的定时任务
1 | crontab -e ## 编辑任务 |
Crontab 的时间格式由五个字段组成,分别表示分钟、小时、日期、月份和星期几。
使用 cron 表达式,工具 https://tool.lu/crontab/
为了避免证书过期,设置一个定时任务每隔 3 个月,15 号自动续期证书并重启 Nginx:1
0 0 15 */3 * root cd /root && docker-compose run --rm certbot renew --force-renewal && docker-compose restart nginx
--force-renewal 强制续签
保存后,定时任务将自动运行续签。
使用 linux 自带的 cron.service 定时任务,执行命令1
2
3systemctl status cron.service
systemctl stop cron.service
systemctl start cron.service
参考地址
https://letsencrypt.org/
https://certbot.eff.org/