如果你在 Docker 容器中運行 Nginx 并希望使用 Certbot 獲取和管理 SSL 證書,可以使用 Certbot 的官方 Docker 鏡像來完成這項工作。以下是使用 Docker 和 Certbot 獲取 SSL 證書并配置 Nginx 的詳細步驟:
1. 拉取 Certbot Docker 鏡像
首先,確保你已經安裝了 Docker。然后,拉取 Certbot 的官方 Docker 鏡像:
docker pull certbot/certbot
2. 停止 Nginx 容器
在獲取 SSL 證書時,Certbot 需要綁定 80 端口,因此需要暫時停止 Nginx 容器:
docker stop <nginx-container-name>
將 <nginx-container-name>
替換為你的 Nginx 容器名稱。
3. 獲取 SSL 證書
使用 Certbot Docker 容器獲取 SSL 證書。以下命令將獲取證書并存儲在本地目錄中(例如 /etc/letsencrypt
):
docker run -it --rm \-v /etc/letsencrypt:/etc/letsencrypt \-v /var/lib/letsencrypt:/var/lib/letsencrypt \-v /path/to/your/webroot:/var/www/html \certbot/certbot certonly --webroot \--webroot-path /var/www/html \--email your-email@example.com \--agree-tos \--no-eff-email \-d example.com -d www.example.com
請將以下內容替換為你的實際值:
/path/to/your/webroot
:替換為你的 Web 根目錄路徑。your-email@example.com
:替換為你的電子郵件地址。example.com
和www.example.com
:替換為你的域名。
4. 配置 Nginx 使用 SSL 證書
在 Nginx 配置文件中設置使用新獲取的 SSL 證書。以下是一個示例配置:
server {listen 80;server_name example.com www.example.com;location /.well-known/acme-challenge/ {root /var/www/html;}location / {return 301 https://$host$request_uri;}
}server {listen 443 ssl;server_name example.com www.example.com;ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;ssl_protocols TLSv1.2 TLSv1.3;ssl_ciphers HIGH:!aNULL:!MD5;location / {root /var/www/html;index index.html index.htm;}
}
將 example.com
替換為你的域名,并確保證書路徑與實際路徑一致。
5. 啟動 Nginx 容器
在更新了 Nginx 配置后,重新啟動 Nginx 容器:
docker start <nginx-container-name>
6. 設置自動續訂
Certbot 的證書有效期為 90 天,需要設置自動續訂。可以通過創建一個 cron job 來自動運行續訂命令:
0 0,12 * * * docker run -it --rm \-v /etc/letsencrypt:/etc/letsencrypt \-v /var/lib/letsencrypt:/var/lib/letsencrypt \-v /path/to/your/webroot:/var/www/html \certbot/certbot renew --webroot --webroot-path /var/www/html --quiet
這行命令將每天兩次檢查和續訂證書。
通過以上步驟,你可以使用 Docker 中的 Certbot 容器來獲取和管理 SSL 證書,并在 Docker 中運行的 Nginx 服務器上配置 SSL。