在 Docker 环境中为 Nginx 配置 HTTPS 与 SSL 证书
前置环境准备
在开始配置之前,请确保基础运行环境已准备就绪。本文基于 CentOS 7.9 操作系统,并使用 Docker 容器化部署 Nginx。Nginx 容器需要同时暴露 80(HTTP)和 443(HTTPS)端口。此外,需提前完成域名的解析配置以及 SSL 证书(包含公钥和私钥文件)的申请与下载。
Nginx 核心配置
在 Nginx 的主配置文件 nginx.conf 中,我们需要定义多个 server 块来处理不同域名的请求,并为特定域名启用 SSL 加密。以下配置展示了静态资源服务、普通 HTTP 反向代理以及 HTTPS 反向代理的综合应用场景。
worker_processes auto;
events {
worker_connections 2048;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
# 基础静态资源服务
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html/static;
index index.html;
}
}
# 业务服务 A (HTTP 访问)
server {
listen 80;
server_name example.com api.example.com;
location / {
proxy_pass http://192.168.1.100:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
# 业务服务 B (HTTP 访问)
server {
listen 80;
server_name web.example.com;
location / {
proxy_pass http://192.168.1.100:8081;
proxy_set_header Host $host;
}
}
# 业务服务 A (HTTPS 加密访问)
server {
listen 443 ssl;
server_name api.example.com;
# 指定 SSL 证书和私钥路径
ssl_certificate /etc/nginx/certs/api.example.com.crt;
ssl_certificate_key /etc/nginx/certs/api.example.com.key;
# SSL 性能与安全优化参数
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4;
ssl_prefer_server_ciphers on;
location / {
proxy_pass http://192.168.1.100:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
HTTP 到 HTTPS 的重定向策略
为了保证数据传输的安全性,通常需要将特定域名的所有 HTTP 请求强制重定向至 HTTPS。可以通过在 nginx.conf 中添加独立的 server 块并使用 return 301 指令来实现,这种方式比传统的 rewrite 正则匹配性能更高且语义更清晰。
server {
listen 80;
server_name secure.example.com;
# 永久重定向到 HTTPS
return 301 https://$host$request_uri;
}
Docker 容器部署与目录挂载
为了让 Nginx 容器能够读取宿主机的配置文件和 SSL 证书,需要合理规划目录结构并进行数据卷挂载。首先在宿主机上创建用于存放证书的目录:
mkdir -p /opt/nginx/certs
将申请好的 .crt 和 .key 文件上传至该目录后,执行以下命令启动 Nginx 容器:
docker run -d \
--name nginx_https_gateway \
--restart always \
-p 80:80 \
-p 443:443 \
-v /opt/nginx/conf/nginx.conf:/etc/nginx/nginx.conf:ro \
-v /opt/nginx/html:/usr/share/nginx/html \
-v /opt/nginx/logs:/var/log/nginx \
-v /opt/nginx/certs:/etc/nginx/certs:ro \
nginx:latest
上述命令中,:ro 参数表示以只读方式挂载配置文件和证书目录,以提升容器的安全性。确保宿主机的 /opt/nginx/conf/ 目录下已存在修改好的 nginx.conf 文件。
验证 SSL 证书生效
容器启动后,Nginx 会自动加载最新的配置。通过浏览器访问配置了 HTTPS 的域名(如 https://api.example.com),检查地址栏是否显示安全锁图标。点击证书详情,确认颁发的域名和有效期与申请的 SSL 证书信息一致,即表明 HTTPS 反向代理配置成功。