# Nginx 基础配置

# 1. Nginx Docker 启动

# docker run 部署

  1. 拉取镜像: docker pull nginx:latest

  2. 创建宿主机目录: mkdir -p /opt/nginx/{conf,conf.d,html,logs}

  3. 获取 Nginx 默认配置文件

    • 启动临时容器: docker run --name nginx-temp -d nginx:latest

    • 容器内的配置文件和配置目录复制到宿主机

      • docker cp nginx-temp:/etc/nginx/nginx.conf /opt/nginx/conf/

      • docker cp nginx-temp:/etc/nginx/conf.d /opt/nginx/conf/

      • docker cp nginx-temp:/usr/share/nginx/html/. /opt/nginx/html/

  4. 停止并删除临时容器

    • docker stop nginx-temp && docker rm nginx-temp
  5. 启动 Nginx 容器

docker run -d \
  --name nginx \
  --restart=always \
  -p 80:80 \
  -v /opt/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \
  -v /opt/nginx/conf/conf.d:/etc/nginx/conf.d \
  -v /opt/nginx/html:/usr/share/nginx/html \
  -v /opt/nginx/logs:/var/log/nginx \
  nginx:latest

# docker compose 部署

  1. 创建 docker-compose.yml 文件
# 目录下创建 docker-compose.yml 文件 < 创建 /opt/nginx/ 等相关目录 >
version: '3'
services:
  nginx:
    image: nginx:latest
    container_name: nginx
    restart: always
    ports:
      - "80:80"
    volumes:
      - /opt/nginx/conf/nginx.conf:/etc/nginx/nginx.conf
      - /opt/nginx/conf/conf.d:/etc/nginx/conf.d
      - /opt/nginx/html:/usr/share/nginx/html
      - /opt/nginx/logs:/var/log/nginx
  1. 启动服务
# 在 docker-compose.yml 文件目录下执行以下命令
docker-compose up -d
  1. 查看容器状态,验证安装
docker ps | grep nginx

# 2.Nginx SSL 配置

# 1.Nginx config 配置

配置 HTTP 到 HTTPS 的重定向以及 HTTPS 服务

#user  root;
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    client_max_body_size 200m;
    # HTTP 服务器,用于处理 Certbot 验证和重定向
    server {
        listen 80;
        server_name your_domain.com www.your_domain.com; # 域名解析
        # Certbot 验证路径
        location /.well-known/acme-challenge/ {
            root /var/www/certbot;
        }
        # 其余请求重定向到 HTTPS
        location / {
            return 301 https://$host$request_uri;
        }
    }
    
    # HTTPS 服务器
    server {
        listen 443 ssl;
        server_name your_domain.com www.your_domain.com;	# 域名解析
        # Let's Encrypt 证书路径
        ssl_certificate /etc/letsencrypt/live/your_domain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/your_domain.com/privkey.pem;
        # SSL 优化配置
        ssl_protocols TLSv1.2 TLSv1.3;	# 指定服务器接受的 TLS 版本
        ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';	# 指定服务器的握手加密算法套件列表
        ssl_session_cache shared:SSL:10m;	#  SSL 会话缓存,指定 TLS 会话参数存储大小
        ssl_session_timeout 1d;	# 设置缓存的 TLS 会话有效期为 1 天
		
		# 指定根目录文件位置和首页页面
        location / {
            root /usr/share/nginx/html;
            index index.html;
        }
        # 同样保留验证路径
        location /.well-known/acme-challenge/ {
            root /var/www/certbot;
        }
        
        # 错误信息页面配置
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

# 2. Nginx 容器信息配置

编写 docker-compose.yml , 配置 nginx 相关信息

version: '3.8'
services:
  nginx:
    image: nginx:alpine
    container_name: nginx
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./conf.d:/etc/nginx/conf.d
      - ./cert:/etc/letsencrypt
      - ./html:/usr/share/nginx/html
      - certbot_www:/var/www/certbot
    restart: unless-stopped

# 3.SSL 证书申请

Let's Encrypt 免费证书

  • Certbot 官方工具,开箱即用,插件少
  • acme.sh 轻量级工具,自定义灵活度高
特性 Certbot acme.sh
实现语言 Python Shell
安装方式 系统包管理器 (apt/yum) 官方脚本 ( curl )
Nginx 集成 官方插件,自动修改配置 需手动指定证书路径和重载命令
DNS 验证 支持,但插件相对较少 支持广泛,几乎涵盖所有主流 DNS 服务商
通配符证书 支持 (需 DNS 验证) 支持,且配置更为简便
适用场景 追求开箱即用,希望与 Nginx 深度集成的用户 追求轻量、灵活,或需要申请通配符证书的高级用户

Certbot 配置 :

  • docker-compose.yml 中添加 certbot 容器配置
  • docker compose up -d 启动服务容器
# 完整配置
version: '3.8'
services:
  nginx:
    image: nginx:alpine
    container_name: nginx
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./conf.d:/etc/nginx/conf.d
      - ./cert:/etc/letsencrypt
      - ./html:/usr/share/nginx/html
      - certbot_www:/var/www/certbot
    restart: unless-stopped
    depends_on:
      - certbot
  certbot:
    image: certbot/certbot
    container_name: certbot
    volumes:
      - ./cert:/etc/letsencrypt
      - certbot_www:/var/www/certbot
    # 首次启动时获取证书,然后进入循环检查续期
    command: >
      sh -c '
      if [ ! -f "/etc/letsencrypt/live/your_domain.com/fullchain.pem" ]; then
        certbot certonly --webroot -w /var/www/certbot -d your_domain.com -d www.your_domain.com --email your_email@example.com --agree-tos --noninteractive;
      fi;
      while :; do
        sleep 12h;
        certbot renew;
      done'
    restart: unless-stopped
volumes:
  certbot_www:

acme.sh 配置 :

  • 安装 acme.sh : curl https://get.acme.sh | sh -s email=my@example.com

  • 重新加载 shell 配置文件,让 acme.sh 命令生效 : source ~/.bashrc

  • 证书申请 :

    • HTTP 验证 (适合有 Web 服务器的用户) : acme.sh --issue -d example.com -d www.example.com --webroot /home/wwwroot/example.com/

      • 优点:简单,无需配置 API。
      • 缺点:无法申请泛域名证书,(如 *.example.com )
    • DNS API 验证 (支持泛域名), 以 Cloudflare 为例

      • 设置环境变量: export CF_Token="Cloudflare_API_Token" , export CF_Account_ID="Cloudflare_Account_ID"
    • 签发证书: acme.sh --issue --dns dns_cf -d example.com -d "*.example.com"

    • 安装证书到 Nginx

    • 验证自动续期

# 安装 acme.sh
curl https://get.acme.sh | sh -s email=my@example.com
# 证书申请: HTTP 验证,acme.sh 会自动在网站根目录生成一个验证文件
acme.sh --issue -d example.com -d www.example.com --webroot /home/wwwroot/example.com/ --nginx  # --webroot 设置网站根目录
# 证书申请:  DNS API 验证(推荐,支持泛域名
# 获取 Cloudflare API Token
# 使用 API Token, 创建一个专门用于编辑 DNS 的令牌。
# 登录 Cloudflare 控制台。
# 点击右上角头像 -> 我的个人资料 (My Profile) -> API 令牌 (API Tokens)。
# 点击 创建令牌 (Create Token)。
# 选择 编辑区域 DNS (Edit zone DNS) 模板(点击 “使用模板”)。
# 配置权限:
# 权限:保持默认的 Zone -> DNS -> Edit。
# 区域资源:选择 特定区域 (Specific zone),在下拉菜单中选中你要签发证书的域名(例如 example.com)。
# 点击 继续显示摘要,然后点击 创建令牌。
# 填入刚 Cloudflare 的 API Token
export CF_Token="你的_Cloudflare_API_Token"
# 填入你的 Cloudflare 账户 ID (可选,但在某些复杂账户结构下推荐)
# 获取方式:Cloudflare 右侧边栏 -> 概述 -> 复制 "帐户 ID"
export CF_Account_ID="你的_Cloudflare_Account_ID"
# 签发证书,使用 dns_cf 插件进行签发
# -d example.com: 主域名
# -d *.example.com: 通配符域名(覆盖所有子域名)
acme.sh --issue --dns dns_cf -d example.com -d "*.example.com"
# 安装证书到 Nginx
#--key-file: 私钥路径。
#--fullchain-file: 完整证书链路径。
#--reloadcmd: 核心参数。当证书自动续期后,该命令会自动执行,重载 Nginx 使新证书生效
sudo acme.sh --install-cert -d example.com \
--key-file       /etc/nginx/ssl/example.com.key \
--fullchain-file /etc/nginx/ssl/example.com.crt \
--reloadcmd      "docker restart nginx"
# 验证自动续期
# acme.sh 安装时会自动添加一个 Cron 定时任务,每天凌晨检查证书有效期
crontab -l
# 手动测试续期(Dry Run):
# 为了确认自动续期流程(包括重载 Nginx)是否正常工作,可以执行模拟续期
# 如果输出显示 Renew success 且没有报错,说明自动续期配置完美
acme.sh --renew -d example.com --dry-run
# 确认域名是否真的签发成功
acme.sh --list

注意事项 :

  • 申请证书前,nginx 配置文件中证书路径部分需注释掉,否则会导致 nginx 报错
  • 证书申请成功后,切勿直接使用 ~/.acme.sh/ 目录下的证书文件
  • 使用 --install-cert 命令,证书自动续期后,自动将新证书复制到相同位置
  • nginx 配置文件, ssl_certificate 指令必须指向 fullchain.cer (或 fullchain.pem ) 文件,而不是域名对应的 .cer 文件