【Docker】快速部署 Certbot 并为 Nginx 服务器配置 SSL/TLS 证书

【Docker】快速部署 Certbot 并为 Nginx 服务器配置 SSL/TLS 证书

引言

Certbot 是一个免费的开源工具,用于自动化管理和获取 SSL/TLS 证书,主要用于与 Let's Encrypt 证书颁发机构交互。

步骤

  1. Nginx 挂载 certbot 文件夹。
bash 复制代码
docker run -d \
  --name nginx \
  -p 80:80 \
  -p 443:443 \
  -v "$(pwd)/nginx/nginx.conf:/etc/nginx/nginx.conf" \
  -v "$(pwd)/nginx/conf.d:/etc/nginx/conf.d" \
  -v "$(pwd)/nginx/log:/var/log/nginx" \
  -v "$(pwd)/nginx/html:/usr/share/nginx/html" \
  -v "$(pwd)/certbot/www:/usr/share/certbot/www:ro" \
  -v "$(pwd)/certbot/ssl:/usr/share/certbot/ssl:ro" \
  --restart always \
  nginx:latest
  1. 修改 Nginx 配置文件 default.conf。
bash 复制代码
server {
    listen       80;
    listen  [::]:80;
    server_name  example.com www.example.com;

    location /.well-known/acme-challenge/ {
        root /usr/share/certbot/www;
    }

    location / {
        root   /usr/share/nginx/html;
        try_files $uri $uri/ /index.html last;
        index  index.html index.htm;
    }
}
  1. 创建证书(仅需运行一次)
bash 复制代码
docker run --rm \
  -v "$(pwd)/www:/usr/share/certbot/www:rw" \
  -v "$(pwd)/ssl:/etc/letsencrypt:rw" \
  certbot/certbot certonly \
  --webroot -w /usr/share/certbot/www \
  -d example.com \
  -d www.example.com \
  --non-interactive \
  --agree-tos \
  --expand \
  -m example@example.com
  1. 修改 Nginx 配置文件 default.conf,启用 SSL 证书。
bash 复制代码
server {
    listen       80;
    listen  [::]:80;
    server_name  example.com www.example.com;

    location /.well-known/acme-challenge/ {
        root /usr/share/certbot/www;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}

server {
    listen       443 ssl;
    listen  [::]:443 ssl;
    server_name  example.com www.example.com;

    ssl_certificate /usr/share/certbot/ssl/live/example.com/fullchain.pem;
    ssl_certificate_key /usr/share/certbot/ssl/live/example.com/privkey.pem;

    location / {
        root   /usr/share/nginx/html;
        try_files $uri $uri/ /index.html last;
        index  index.html index.htm;
    }
}
  1. https 启用成功
相关推荐
梦想的颜色1 小时前
【Docker原理】Docker 容器一文打尽:生命周期、环境管控、迁移备份、日志进程排查、垃圾清理
运维·docker·容器·容器生命周期·容器日志排查·容器迁移备份·容器进程管理
欢呼的太阳3 小时前
数据库设计Step by Step (10)——范式化
服务器·数据库·oracle
夜雪一千3 小时前
Python enumerate() 函数完整详解:遍历同时获取索引,告别手动计数
服务器·windows·python
ITKEY_4 小时前
macOS brew 安装的nginx 文件在哪里?
运维·nginx·macos
Felix-lxd5 小时前
Ubuntu 22.04 配置 Nginx
linux·nginx·ubuntu
大E帝国子民15 小时前
MacOS 安装Seismic Unix
服务器·macos·unix
德福危险6 小时前
富有想象力的XSS盲打:靶机练习之Tempus_fugit5
服务器·网络·xss
孫治AllenSun6 小时前
【Nginx】配置参数和使用案例
运维·nginx
极客先躯9 小时前
高级java每日一道面试题-2026年03月30日-实战篇[Docker]-如何监控容器的网络流量?
java·运维·docker·容器·prometheus·高级面试
brave_zhao10 小时前
nginx的进程架构
java·学习·nginx