【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 启用成功
相关推荐
n***271919 分钟前
SQL Server 中行转列
运维·服务器
q***829134 分钟前
Nginx中$http_host、$host、$proxy_host的区别
运维·nginx·http
q***14641 小时前
RustDesk搭建公网中继服务器远控内网机器(完整版)
运维·服务器
zhaqonianzhu1 小时前
【保姆级】无外网 Linux 服务器用 VSCode 通义灵码:SSH 代理配置全流程
linux·服务器·vscode
o***Z4481 小时前
Docker镜像安全扫描
安全·docker·容器
@CLoudbays_Martin111 小时前
钓鱼网站应该怎么判断?
服务器·网络·安全
EasyCVR2 小时前
视频汇聚平台EasyCVR服务器使用WiFi网卡时,为何无法向级联平台发送注册?
运维·服务器
赋创小助手2 小时前
英特尔确认取消 8 通道 Diamond Rapids:服务器 CPU 战局再度升级
服务器·图像处理·人工智能·深度学习·计算机视觉·自然语言处理·自动驾驶
l***O5202 小时前
Docker微服务
docker·微服务·容器
1***Q7842 小时前
Docker计算机视觉应用
计算机视觉·docker·容器