背景说明
Let’s Encrypt 提供了免费的SSL证书发放,但是存在过期时间,需要定期重新生成证书。就想通过Docker +cron 自动定时签发证书。
参考文档
certbot docker部署: https://eff-certbot.readthedocs.io/en/stable/install.html#alternative-1-docker
certbot 使用教程: https://eff-certbot.readthedocs.io/en/stable/using.html#certbot-commands
其他教程博客:https://blog.newnius.com/automated-letsencrypt-certbot-with-docker.html
前置知识点
Let’s Encrypt :提供免费SSL证书发放的机构,但是发放的证书只有3个月时效。
certbot :Let’s Encrypt 推荐的签发服务。
docker images certbot/certbot : certbot的docker服务,启动后cmd为certbot,所以用的时候只要带上后续参数就行了
前置要求
Docker服务
Nginx服务(也不是必要,只是本教程使用的是Nginx进行验证)
教程
一、基本原理
- Nginx将
/.well-known路由到特定文件夹比如:/var/www/html/certbot - 通过certbot下载验证文件,并将文件挂载到文件夹:
/var/www/html/certbot - 此时 Let’s Encrypt 会通过 http 请求到nginx服务
http://xxxx//.well-known下的验证文件 - 验证通过后certbot就会下载 Let’s Encrypt 证书下载到特定的文件夹:
/etc/letsencrypt/ - 配置Nginx的https证书地址,重启就完成了https认证签发。
二、配置Nginx
server {
...
// 主要添加配置
location ~ /.well-known {
allow all;
root /var/www/html/certbot/;
}
...
}
由于我是Docker运行的Nginx还需要将文件夹挂载出去 -v ./html/certbot:/var/www/html/certbot/
三、运行certbot容器验证
docker run -it --rm --name certbot \
-v "./letsencrypt/:/etc/letsencrypt/" \
-v "./html/certbot/:/var/www/html/certbot/" \
certbot/certbot certonly -n --no-eff-email --email example@qq.com --agree-tos --webroot -w /var/www/html/certbot/ -d example.com
-v "./letsencrypt/:/etc/letsencrypt/"ssl证书的存放位置,需要挂载出去共享给到Nginx-v "./html/certbot/:/var/www/html/certbot/"Nginx认证文件位置,需要和certbot同一挂载路径--email example@qq.com证书要过期时会收到提醒邮件--webroot -w /var/www/html/certbot/Nginx认证文件存储位置example.com你的域名
四、配置Nginx并重启
// 原有 http 80端口配置自动转发到 https 443
server {
listen 80;
server_name example.com;
return 301 https://example.com$request_uri;
}
// https 配置
server {
...
// 443 端口与域名配置
listen 443 ssl;
server_name example.com;
// 证书位置
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
location ~ /.well-known {
allow all;
root /var/www/html/certbot/;
}
....
}
Nginx docker重启时需要添加配置,挂载证书-v ./nginx/letsencrypt:/etc/letsencrypt,开放端口443-p 443:443
编写定时任务
编写脚本文件:/crontab/run_certbot.sh
docker run -it --rm --name certbot \
-v "./letsencrypt/:/etc/letsencrypt/" \
-v "./html/certbot/:/var/www/html/certbot/" \
certbot/certbot certonly -n --no-eff-email --email example@qq.com --agree-tos --webroot -w /var/www/html/certbot/ -d example.com
docker restart nginx
添加执行权限
chmod +x run_certbot.sh
编辑crontab
crontab -e
添加定时任务,每个月1号执行一次
0 0 1 * * /crontab/run_certbot.sh