使用certbot自动获取SSL证书

Certbot 是一个由 EFF(Electronic Frontier Foundation) 推出的开源工具,用于自动从 Let’s Encrypt 获取免费 SSL/TLS 证书,并自动完成证书安装与续期。它极大地简化了为网站启用 HTTPS 的流程。

本文介绍在debian12上使用certbot。

sudo apt update
sudo apt install certbot

sudo docker-compose down  # 停止容器以释放80端口

sudo certbot certonly --standalone -d www.laowunotes.com

# 获取证书后,修改 docker-compose.yml 文件挂载新证书

修改 docker-compose.yml 配置

sudo vi docker-compose.yml

将证书挂载部分修改为:

volumes:
  - ../:/var/www/html
  - ./apache/site_host.conf:/etc/apache2/sites-available/000-default.conf
  # 使用 Let's Encrypt 证书
  - /etc/letsencrypt/live/laowunotes.com/fullchain.pem:/etc/apache2/ssl/server.crt
  - /etc/letsencrypt/live/laowunotes.com/privkey.pem:/etc/apache2/ssl/server.key

 确保证书可被访问

Let’s Encrypt 证书默认权限较严格,需要确保容器可以读取:

# 添加读取权限
sudo chmod -R 755 /etc/letsencrypt/live
sudo chmod -R 755 /etc/letsencrypt/archive

 更新 Apache 配置

您的 Apache 配置文件site_host.conf 已经正确配置了,不需要修改。它已经引用了:

SSLCertificateFile /etc/apache2/ssl/server.crt
SSLCertificateKeyFile /etc/apache2/ssl/server.key

这正是我们在 docker-compose.yml 中挂载 Let’s Encrypt 证书的位置。

重启 Docker 容器

# 停止当前容器
sudo docker-compose down
# 重新启动容器
sudo docker-compose up -d

自动续期

如果在安装完certbot时,看到Certbot has set up a scheduled task to automatically renew this certificate in the background.,就表示自动续期已经自动设置了。

但您还需要确保证书更新后重启 Docker 容器。创建一个续期钩子脚本:

sudo mkdir -p /etc/letsencrypt/renewal-hooks/post
sudo vi /etc/letsencrypt/renewal-hooks/post/restart-docker.sh

添加以下内容:

#!/bin/bash
cd /your-docker-file/path
docker-compose restart web

设置执行权限:

sudo chmod +x /etc/letsencrypt/renewal-hooks/post/restart-docker.sh

最后重启容器:

sudo docker-compose restart

相关阅读:在 Debian 12 上确定 Certbot 是否会自动续期

使用certbot自动获取SSL证书》有一个想法

  1. Pingback引用通告: 在 Debian 12 上确定 Certbot 是否会自动续期 – 老吴笔记

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注