【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 启用成功
相关推荐
XR风云14 分钟前
docker buildx 忽略容器镜像服务的证书校验的方法
运维·docker·容器
闲云自留地1 小时前
课后作业-20260806-Linux iSCSI服务器
linux·运维·服务器
风雨_831 小时前
轻量级 Nginx 日志分析和可视化平台 NginxPulse安装
运维·nginx
智购科技智能售货柜1 小时前
自动售货机商品识别YOLO模型训练实战:从6万张图片到98%识别率的完整复盘~YH
运维·服务器·数据库·人工智能·redis·物联网·yolo
若无情我 纸小铭1 小时前
Nginx学习笔记(二) Nginx--connection&request
笔记·学习·nginx
SeaTunnel1 小时前
Apache SeaTunnel 提交一个任务都经过了什么?
java·大数据·服务器·apache·etl·seatunnel
xixingzhe21 小时前
net::ERR_INCOMPLETE_CHUNKED_ENCODING解决
nginx
.冰块.1 小时前
P-SAN 实战:CentOS7 搭建 iSCSI Target 共享块存储
linux·服务器·iscsi
Kina_C1 小时前
Keepalived 单播模式实战:跨网络高可用的关键配置
linux·服务器·网络·keepalived
IKUN家族2 小时前
常见的依懒
java·服务器·数据库