Docker 强制 HTTPS 怎么做:Nginx、Traefik、Caddy 跳转、证书与排错实战
Docker 本身不会自动把 HTTP 改成 HTTPS,强制跳转应在反向代理层完成:保留 80 端口用于 ACME 与 301,443 终止 TLS,典型 Nginx 配置为 return 301 https://$host$request_uri;,证书使用 Let's Encrypt 的 fullchain.pem。 Nginx 1.26 + certbot 2.x 方案:挂载 /etc/letsencrypt 与 /var/www/certbot,HTTP 到 HTTPS 用 301,HSTS 建议从 max-age=300 测试后升到 31536000。 Traefik v3 用 redirectscheme 中间件并设置 permanent=true;Caddy 2.8 默认自动 HTTPS,反向代理后通常无需手写跳转。 验证命令:curl -I http://example.com 应返回 301 且 Location 指向 https://;openssl s_client -connect example.com:443 -servername example.com 检查证书链;docker compose config 检查端口映射与挂载。
为什么执行 docker run -p 80:80 后,http://IP 仍能直接打开? 因为 Docker Engine 24.0–27.x 只负责镜像、容器网络与端口映射,本身不提供 TLS 终止或 HTTP→HTTPS 重定向(据 Docker Engine 文档)。-p 80:80 通过 iptables DNAT(userland-proxy 默认 true)把外部 TCP 80 原样送到容器,浏览器不会自动升级协议;Docker 的转发机制只改变路径,不改变协议。
典型生产链路应只有唯一公网入口:CDN/云 LB → Nginx 1.26 或 Traefik v3 → 应用容器。应用只 expose 3000,绝不发布 80/443;否则 http://IP:3000 可绕过跳转。这也是 docker 强制https 的边界:跳转放在入口代理,而不是应用容器。
# 1) 创建专用网络
docker network create web
# 2) 应用容器:只暴露给 Docker 网络,不映射到宿主机
docker run -d --name app --network web --expose 3000 myapp:1.0
# 3) Nginx 1.26:只由它发布 80/443
docker run -d --name nginx --network web -p 80:80 -p 443:443
-v "$PWD/site.conf:/etc/nginx/conf.d/default.conf:ro"
-v /etc/letsencrypt:/etc/letsencrypt:ro nginx:1.26-alpine
# 4) 验证:app 不应有宿主机端口;HTTP 应返回 308 和 https Location
docker port app # 期望无输出
curl -sI http://127.0.0.1/ | head -n 3
# site.conf(Nginx 1.26)
server {
listen 80;
server_name example.com;
# 测试期先 302,确认无误再换 308,避免浏览器缓存污染
return 308 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; # 确认全站 HTTPS 后再开
location / {
proxy_pass http://app:3000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme; # 443 server 中即 https
}
}
301 是永久重定向且可能被浏览器缓存,308 同样永久但保留 POST/PUT 方法(据 RFC 9110)。登录、支付、API 建议 308;Nginx 写作 return 308 https://$host$request_uri;,测试阶段用 302。HSTS 只在浏览器成功收到 HTTPS 响应后生效,Strict-Transport-Security 的 max-age 默认没有;首次 HTTP 访问仍要靠 80 端口返回 301/308,所以没有 DNS-01 兜底时不要直接关闭 80(据 Let’s Encrypt 与 Mozilla MDN 文档)。
| 状态码 | 语义 | 方法保留 | 缓存风险 | 建议场景 |
|---|---|---|---|---|
| 301 | 永久重定向 | 历史实现可能改为 GET | 高,可能被浏览器长期缓存 | 稳定域名迁移 |
| 302 | 临时重定向 | 通常保留 | 低(默认不永久缓存) | 上线测试 |
| 308 | 永久重定向 | 强制保留 POST/PUT | 高 | 登录、支付、API |
反向代理必须传 X-Forwarded-Proto https,否则 Spring Boot 3.2 需 server.forward-headers-strategy=framework、Express 4.18 需 app.set('trust proxy', 1),应用可能生成 http 链接并触发混合内容或重定向循环。若 CDN 回源协议设为 HTTP,源站 301 到 HTTPS 后 CDN 再回源 HTTP 会形成循环,浏览器常见报错 ERR_TOO_MANY_REDIRECTS;需把回源协议改为 HTTPS 或 Follow。做 docker 强制https 时,先检查这条链路,再谈证书与配置。
Docker 强制 HTTPS 的完整实操步骤(Nginx 1.26 + Let's Encrypt 示例)
这一节按“先 80 后 443”的顺序走,核心思路是:先让 ACME 的 http-01 校验路径能通,再切换成 301 跳转。顺序颠倒是最常见的翻车点——一旦 80 端口整体 301,Let’s Encrypt 的校验请求会被重定向到还没证书的 443,续期直接失败。据 Let’s Encrypt 文档,http-01 校验必须能从公网 80 端口访问 /.well-known/acme-challenge/,遵循 RFC 8555(ACME v2)协议。
步骤 1:准备域名与目录
先把 example.com 和 www.example.com 的 A 记录指向宿主机公网 IP,等 TTL 生效后用 dig 确认:
# 返回的 IP 必须与宿主机公网出口一致,否则 ACME 校验必然失败
dig +short example.com
dig +short www.example.com
# 建目录,755 让容器内非 root 进程也能读
mkdir -p /srv/https-demo/nginx/conf.d
/srv/https-demo/certbot/conf
/srv/https-demo/certbot/www
chmod -R 755 /srv/https-demo
# 私钥目录建议再收紧(certbot 自己会把 privkey.pem 设为 600)
chmod 700 /srv/https-demo/certbot/conf
步骤 2:确认版本与端口占用
docker --version # 需 >= 26.1,示例输出:Docker version 26.1.4, build 5650f9b
docker compose version # 需 >= v2.27.0
# 无输出才表示 80/443 空闲;有输出先 systemctl stop nginx
ss -lntp | grep -E ':80|:443'
步骤 3:先只起 80 端口和 ACME 路径
nginx/conf.d/default.conf 里此时不要写跳转:
server {
listen 80;
server_name example.com www.example.com;
# Certbot webroot 模式把挑战文件写到这个目录
location ^~ /.well-known/acme-challenge/ {
root /var/www/certbot; # 容器内路径,映射到宿主 certbot/www
}
location / {
return 200 "http okn"; # 步骤 5 会改成 301
}
}
对应的 Compose 片段(关键在卷映射):
services:
nginx:
image: nginx:1.26-alpine
ports: ["80:80", "443:443"]
volumes:
- ./nginx/conf.d:/etc/nginx/conf.d:ro
- ./certbot/conf:/etc/letsencrypt:ro
- ./certbot/www:/var/www/certbot:ro
app:
image: node:20-alpine # 示例后端,监听 3000
expose: ["3000"]
certbot:
image: certbot/certbot:v2.11.0
volumes:
- ./certbot/conf:/etc/letsencrypt
- ./certbot/www:/var/www/certbot
entrypoint: ["certbot"]
cd /srv/https-demo && docker compose up -d nginx
# 404 是预期结果:说明路径可达但 test 文件不存在
curl -s -o /dev/null -w '%{http_code}n'
http://example.com/.well-known/acme-challenge/test
步骤 4:申请证书
docker run --rm
-v /srv/https-demo/certbot/conf:/etc/letsencrypt
-v /srv/https-demo/certbot/www:/var/www/certbot
certbot/certbot:v2.11.0 certonly --webroot
-w /var/www/certbot
-d example.com -d www.example.com
--email admin@example.com --agree-tos --no-eff-email
成功时会打印:
Successfully received certificate.
Certificate is saved at: /etc/letsencrypt/live/example.com/fullchain.pem
Key is saved at: /etc/letsencrypt/live/example.com/privkey.pem
注意目录名取第一个 -d 的域名,www 会写进 SAN;漏掉 -d www 会导致 www 访问报 NET::ERR_CERT_COMMON_NAME_INVALID。
步骤 5:切换到强制 HTTPS
server {
listen 80;
server_name example.com www.example.com;
location ^~ /.well-known/acme-challenge/ {
root /var/www/certbot; # 必须保留,否则续期失败
}
# 用 $host 而非 $server_name,域名未匹配时也不会跳错
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
http2 on; # nginx 1.25.1+ 独立指令
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_session_cache shared:SSL:10m;
location / {
proxy_pass http://app:3000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto https; # 后端据此判断原始协议
proxy_set_header X-Real-IP $remote_addr;
}
}
| 指令 | 示例值 | 默认值 | 说明 |
|---|---|---|---|
listen |
443 ssl |
80 | 加密端口必须显式带 ssl 关键字,否则握手失败 |
http2 |
on |
off | 旧写法 listen 443 ssl http2 自 1.25.1 起弃用并告警 |
ssl_protocols |
TLSv1.2 TLSv1.3 |
1.23.4 起为 TLSv1.2 TLSv1.3 |
更早版本默认含 TLSv1/1.1,需显式收窄 |
ssl_certificate |
fullchain.pem |
— | 用 cert.pem 会缺中间证书,安卓与部分 Java 客户端报链错误 |
步骤 6:校验、重载与自动续期
docker compose exec nginx nginx -t
# nginx: configuration file /etc/nginx/nginx.conf test is successful
docker compose exec nginx nginx -s reload
curl -sI http://example.com | head -n 3
# HTTP/1.1 301 Moved Permanently
# Location: https://example.com/
续期先用 dry-run 验证,再写 cron(/etc/cron.d/certbot-renew,权限 644,文件末尾留空行):
# 先验证,输出 "Congratulations, all simulated renewals succeeded"
cd /srv/https-demo && docker compose run --rm certbot renew --dry-run
# 每天 03:17 续期;Let's Encrypt 证书有效期 90 天,官方建议每 60 天左右续一次
17 3 * * * root cd /srv/https-demo && docker compose run --rm certbot renew --quiet && docker compose exec nginx nginx -s reload
renew 只对剩余有效期不足 30 天的证书实际动作,所以每天跑不会触发重复签发和速率限制。到这里,Docker 强制 HTTPS 的闭环就完成了;同一套思路换到 Traefik 或 Caddy 时,差别只在“谁负责申请证书”和“跳转由谁生成”。
配置与命令示例:Nginx、Traefik v3、Caddy 2.8 怎么写?
Nginx 1.26 的 server 块到底该怎么写?关键点只有一个:从 Nginx 1.25.1 起,listen 443 ssl http2; 已被弃用,继续写会在 nginx -t 时输出 warning: the "listen ... http2" directive is deprecated, use the "http2" directive instead,改用独立的 http2 on;(Nginx 1.26 中该指令默认 off)。ACME 校验路径必须放在 return 301 之前,否则 Let’s Encrypt 的 HTTP-01 校验会被跳转打断,报 Invalid response from ...: 301。
# /etc/nginx/conf.d/example.conf —— Nginx 1.26.x 验证通过
server {
listen 80;
server_name example.com www.example.com;
# 必须保留:Let's Encrypt HTTP-01 校验走 80 端口,不能被 301 掉
location ^~ /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 301 https://$host$request_uri; # 301 会被浏览器缓存,调试期可临时改 302
}
}
server {
listen 443 ssl;
http2 on; # 1.25.1+ 新写法,替代 listen 443 ssl http2
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # 必须用 fullchain,含中间证书
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3; # 默认值仅 TLSv1.2/1.3,TLSv1.1 及以下需显式开启
ssl_session_cache shared:SSL:10m; # 默认 none,开启后 10m 约存 4 万会话
ssl_session_timeout 1d;
add_header Strict-Transport-Security "max-age=31536000" always; # 先别加 includeSubDomains
location / {
proxy_pass http://app:3000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto https; # 应用判断 req.secure 的唯一依据
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
docker compose 里证书怎么持久化?certbot 容器不要用 certonly 一次性申请后退出,用 --webroot + 循环 renew 才能长期免维护。Let’s Encrypt 官方文档明确续期建议为到期前 30 天,因此每 12 小时轮询一次是安全的(renew 在未到期时直接跳过)。
# docker-compose.yml —— Docker Compose v2 语法
services:
nginx:
image: nginx:1.26-alpine
ports: ["80:80", "443:443"]
volumes:
- ./nginx/conf.d:/etc/nginx/conf.d:ro
- ./certbot/conf:/etc/letsencrypt:ro # 只读挂载证书
- ./certbot/www:/var/www/certbot:ro # 只读挂载 ACME 校验目录
depends_on: [app]
app:
image: node:20-alpine
expose: ["3000"] # 只在内部网络暴露,不映射到宿主机
certbot:
image: certbot/certbot:v2.11.0
volumes:
- ./certbot/conf:/etc/letsencrypt
- ./certbot/www:/var/www/certbot
entrypoint: /bin/sh -c 'trap exit TERM; while :; do certbot renew --webroot -w /var/www/certbot --quiet; sleep 12h & wait $${!}; done'
Traefik v3 用标签还是配置文件?Traefik v3.0 推荐把路由规则写在容器 label 上,静态配置只保留 entryPoint 与 ACME 解析器。注意 v3 已移除 v2 的部分字段(如 providers.docker.swarmMode),升级时用 traefik version 核对。ACME 账户文件 acme.json 权限必须是 600,否则 Traefik 启动直接报 permissions 644 are too open 并退出。
# docker-compose.yml 中 app 服务的 labels(Traefik v3.0+)
labels:
- traefik.enable=true
- traefik.http.routers.app.rule=Host(`example.com`)
- traefik.http.routers.app.entrypoints=web
- traefik.http.routers.app.middlewares=redirect-to-https
- traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https
- traefik.http.middlewares.redirect-to-https.redirectscheme.permanent=true # 默认 false,即 302
- traefik.http.routers.app-secure.rule=Host(`example.com`)
- traefik.http.routers.app-secure.entrypoints=websecure
- traefik.http.routers.app-secure.tls.certresolver=letsencrypt
# traefik.yml 静态配置片段
entryPoints:
web: { address: ":80" }
websecure: { address: ":443" }
certificatesResolvers:
letsencrypt:
acme:
email: ops@example.com
storage: /acme.json
httpChallenge: { entryPoint: web } # HTTP-01 必须走 80 端口
Caddy 2.8 是不是真的三行就够?是。Caddy 默认监听 80/443,检测到域名即自动向 Let’s Encrypt 申请证书,并把 80 的请求 301 到 443,证书与密钥存放在数据目录 /data(容器内路径,务必挂载卷,否则重启重复申请会触发 Let’s Encrypt 的“每域名每周 50 张”重复证书限流)。关闭自动跳转要写 auto_https off,Caddy 官方文档明确不建议,因为等于放弃 docker 强制 https 的默认保障。
# Caddyfile —— Caddy 2.8.x
example.com {
encode zstd gzip
reverse_proxy app:3000
header Strict-Transport-Security "max-age=31536000; includeSubDomains"
}
| 维度 | Nginx 1.26 | Traefik v3.0 | Caddy 2.8 |
|---|---|---|---|
| 证书申请 | 外挂 certbot 容器 | 内置 ACME,需 acme.json(600) | 内置 ACME,零配置 |
| HTTP→HTTPS | return 301 手写 |
redirectscheme 中间件 | 默认自动 301 |
| 配置生效 | 需 nginx -s reload |
标签变更自动热加载 | 改 Caddyfile 自动重载 |
| 适合场景 | 已有 Nginx 生态、需精细调优 | 多容器动态扩缩容 | 单机小团队、最少运维 |
应用层还要不要兜底?要,但只是兜底——边缘代理漏配时避免明文回源。Express 4.18 必须设 trust proxy,否则 req.secure 恒为 false,会陷入重定向死循环:
app.set('trust proxy', 1); // 信任第一层代理,否则 req.secure 永远 false
app.use((req, res, next) => {
if (req.secure) return next();
return res.redirect(308, 'https://' + req.headers.host + req.originalUrl); // 308 保留 method
});
# Spring Boot 3.2 application.properties
server.forward-headers-strategy=framework # 默认 none,不设则 request.isSecure() 失真
# 配合 WebSecurityConfig 中 http.requiresChannel().anyRequest().requiresSecure()
HSTS 和 OCSP stapling 的坑在哪?据 RFC 6797,HSTS 一旦下发 max-age 就在有效期内不可撤销,因此建议阶梯推进:max-age=300 观察 24 小时 → 86400 → 最终 31536000;加 includeSubDomains 前先确认所有子域都有有效证书,否则子域会整体不可访问。OCSP stapling 需证书链含中间证书(即 fullchain.pem),并显式指定 resolver,否则 Nginx 无法主动拉取 OCSP 响应:
ssl_stapling on; # 默认 off
ssl_stapling_verify on; # 默认 off,需配合 ssl_trusted_certificate 或 fullchain
resolver 1.1.1.1 8.8.8.8 valid=300s;
resolver_timeout 5s;
# 验证:openssl s_client -connect example.com:443 -status | grep -i "OCSP Response Status"
Nginx、Traefik、Caddy 与云负载均衡怎么选?
只有 1-3 个容器、不想写配置,能不能不装 Nginx? 可以。据 Caddy 官方文档,Caddyfile 只写域名和 reverse_proxy,它会自动申请证书、自动把 80 端口 301 到 443、默认启用 OCSP stapling。要不要换成 Nginx 或 Traefik,取决于你已有的资产和容器增减频率,而不是性能差异。
| 方案 | 适用场景 | 强制跳转写法 | 证书管理 | 运维成本 | 备注 |
|---|---|---|---|---|---|
| Nginx 1.26 | 单机多站点、已有 Nginx 经验 | return 301 https://$host$request_uri; |
certbot 2.x 手动/脚本 | 中 | 生态成熟,配置可控 |
| Traefik v3.0 | Docker 动态容器多 | redirectscheme 中间件 permanent=true |
内置 ACME | 中高 | 标签多,适合 Swarm/K8s |
| Caddy 2.8 | 小团队快速上线 | 默认自动 HTTPS | 内置 ACME | 低 | Caddyfile 最短 |
| 云 LB(ALB/CLB) | 托管入口、预算允许 | 监听器 80→443 重定向 | ACM 证书 | 低但按量计费 | 需安全组与回源协议 |
| 应用中间件 | 无反向代理的 PaaS | 代码返回 308 | 手动 | 低但易漏 | 不建议作为唯一入口 |
Nginx 1.26 怎么写 docker 强制https 的跳转? 单独一个 80 端口的 server 块做 301,不要在主站里用 if 判断 scheme:
# /etc/nginx/conf.d/app.conf —— Nginx 1.26 实测
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri; # 保留路径与查询串,比 rewrite 更省
}
server {
listen 443 ssl;
http2 on; # 1.25.1 起取代 listen ... http2
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3; # 显式写死,别依赖旧版本含 TLSv1/1.1 的默认值
add_header Strict-Transport-Security "max-age=31536000" always; # 先不加 preload
location / { proxy_pass http://app:3000; }
}
Traefik v3.0 的标签怎么配? 关键是 redirectscheme.permanent,默认 false 表示 302,改 true 才是 301:
# docker-compose.yml(Traefik v3.0+)
labels:
- "traefik.http.routers.app.rule=Host(`example.com`)"
- "traefik.http.routers.app.entrypoints=websecure"
- "traefik.http.routers.app.tls.certresolver=le"
- "traefik.http.routers.app-http.rule=Host(`example.com`)"
- "traefik.http.routers.app-http.entrypoints=web"
- "traefik.http.routers.app-http.middlewares=to-https"
- "traefik.http.middlewares.to-https.redirectscheme.scheme=https"
- "traefik.http.middlewares.to-https.redirectscheme.permanent=true"
Caddy 2.8 需要写跳转吗? 不需要,默认就有:
example.com {
reverse_proxy app:3000 # 自动签发证书 + 80→443 301 + HSTS 可选
}
用云 LB 时最容易漏什么? 回源协议。AWS ALB 把 80 监听器改为重定向的命令如下(AWS CLI v2),同时要确认目标组协议是 HTTP 还是 HTTPS,否则 X-Forwarded-Proto 与应用判断会打架:
aws elbv2 modify-listener --listener-arn <http-listener-arn>
--default-actions Type=redirect,RedirectConfig='{Protocol=HTTPS,Port=443,StatusCode=HTTP_301}'
HSTS 提醒:
max-age=31536000(1 年)是常见起点;includeSubDomains会覆盖所有子域,只要还有一个 HTTP 子站就会直接不可用;preload提交后撤销周期以月计。先开 max-age=300 观察,再逐级加长。
性能要不要担心? Nginx 静态 TLS 终止在 1 vCPU 上通常可处理数千 QPS;Traefik 默认中间件链更多,Caddy 默认开启 OCSP stapling。在 100Mbps–1Gbps 出口下三者差异通常小于 10%,先压测再换。证书成本方面:Let’s Encrypt 免费、90 天有效,建议每 30 天续期;商业 DV 约 100–500 元/年,OV 约 800–3000 元/年;云 LB 的 ACM 证书免费,但按实例和流量计费。选型落到一句话:已有 Nginx 资产和 certbot 脚本就继续用 Nginx 1.26;容器频繁增减、需要自动发现选 Traefik v3.0;对 SLA 有要求且愿意付费选云 LB。
Docker 强制 HTTPS 常见报错与排查(真实信息)
问:容器一启动就报 nginx: [emerg] cannot load certificate "/etc/letsencrypt/live/example.com/fullchain.pem": BIO_new_file() failed (SSL: error:80000002:system library::No such file or directory),证书明明在宿主机上?
九成是没挂载或挂错层级。注意 fullchain.pem 本身是指向 ../../archive/example.com/ 的软链,只挂 live/ 会断链,必须挂整个 conf 根目录。按 Let’s Encrypt 文档的目录约定,live/ 与 archive/ 是同级兄弟目录。
# 1) 宿主机确认文件与软链真实存在
sudo ls -l ./certbot/conf/live/example.com/
# 2) 容器内确认挂载生效(无输出或报 No such file 即挂载缺失)
docker compose exec nginx ls -l /etc/letsencrypt/live/example.com/
# 3) compose 关键行:挂父目录 + 只读,防止容器改写证书
services:
nginx:
image: nginx:1.27-alpine
volumes:
- ./certbot/conf:/etc/letsencrypt:ro # 必须挂 conf 根,不能只挂 live
- ./certbot/www:/var/www/certbot:ro
问:浏览器报 ERR_TOO_MANY_REDIRECTS,到底谁在循环 301?
典型链路是:Nginx 把 http 301 到 https,但反代给上游时没告诉它”已经是 HTTPS”,应用又 301 一次;或 CDN 回源走 http、源站再 301,形成闭环。先用 curl -I 看 Location 指向哪一层。
curl -I https://example.com # 看 Location 是否又跳回 http://
curl -I http://app:3000 -H 'X-Forwarded-Proto: https' # 验证上游是否认这个头
# Nginx 侧:透传协议,别让框架误判
location / {
proxy_pass http://app:3000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme; # TLS 在本层终止时即 https
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
若外层还有 CDN,$scheme 在回源段会是 http,应改用 map $http_x_forwarded_proto $fwd_proto 兜底,或直接硬写 https。这也是做 Docker 强制 HTTPS 时最容易忽略的一环:跳转只能有一层负责。
问:Mixed Content 警告怎么根治?
报错形如 Mixed Content: The page at 'https://...' was loaded over HTTPS, but requested an insecure resource 'http://...',说明应用用绝对 URL 拼了 http 资源。根治是让框架读 X-Forwarded-Proto(Django 设 SECURE_PROXY_SSL_HEADER,Laravel 设 TrustProxies,Rails 设 config.force_ssl)。临时兜底可加 CSP:
# 仅兜底:浏览器自动把 http 子资源升级为 https
add_header Content-Security-Policy "upgrade-insecure-requests" always;
问:Bind for 0.0.0.0:443 failed: port is already allocated 怎么处理?
- HTTPS配置 · SSL证书安装服务(各种服务器)
- APP/小程序 HTTPS · SSL网站加密证书 · CA证书配置
- NGINX / APACHE / TOMCAT / IIS 证书配置 · SSL证书安装
sudo ss -lntp | grep ':443' # 找到占用 PID/进程名
# 方案 A:停掉宿主机旧 Nginx/Apache
sudo systemctl stop nginx
# 方案 B:只监听回环,由外层代理转发
ports:
- "127.0.0.1:8443:443"
问:容器里 curl: (60) SSL certificate problem: unable to get local issuer certificate?
Alpine 镜像默认不带 CA 包;自签或内部 CA 也需显式导入。update-ca-certificates 会扫描 /usr/local/share/ca-certificates/ 下所有 .crt。
apk add --no-cache ca-certificates && update-ca-certificates # Alpine
cp internal-ca.crt /usr/local/share/ca-certificates/ && update-ca-certificates
问:502 且日志是 connect() failed (111: Connection refused) while connecting to upstream?
协议不匹配:proxy_pass https://app:3000 但上游只说 http,Nginx 会去握手明文端口然后被拒。改成 http://app:3000;若上游确需 TLS,务必配 proxy_ssl_verify on 加可信 CA,proxy_ssl_verify off 只允许出现在调试环境(Nginx 官方文档默认值即为 off)。
| 报错关键词 | 根因 | 一行修复 |
|---|---|---|
BIO_new_file() failed |
证书未挂载 / 只挂了 live 断软链 | 挂 ./certbot/conf:/etc/letsencrypt:ro |
ERR_TOO_MANY_REDIRECTS |
跳转层重复 / 未传协议头 | 补 X-Forwarded-Proto,只保留一层 301 |
Mixed Content |
应用生成绝对 http URL | 信任代理头,或 CSP upgrade-insecure-requests |
port is already allocated |
宿主机 443 被旧进程占用 | 停旧服务或改 127.0.0.1:8443:443 |
unable to get local issuer |
镜像缺 CA 包 / 自签 | update-ca-certificates |
connect() failed (111) |
proxy_pass 协议与上游不符 | 改 http://app:3000 |
如何验证 Docker 强制 HTTPS 已经生效?
问:改完 Nginx/Traefik/Caddy 配置、重启容器之后,怎么确认 docker 强制https 真的生效了?不要只看浏览器地址栏的小锁:那可能只是浏览器自己升级了请求。请按「跳转 → HSTS → 证书 → 容器 → 对外暴露端口 → 混合内容 → 续期」的顺序逐层验证,每一层都有可判定的期望输出。
| 验证层 | 关键命令 | 通过标准 | 不通过通常意味着 |
|---|---|---|---|
| 跳转 | curl -I http://example.com |
HTTP/1.1 301 Moved Permanently 且 Location: https://example.com/ |
80 端口的 server 块缺 return 301 |
| HSTS | curl -sI https://example.com |
strict-transport-security: max-age=31536000 |
add_header 写在 location 内被覆盖,或未 include snippet |
| 证书链 | openssl s_client -showcerts |
Verify return code: 0 (ok) |
只配了 cert.pem 未配 fullchain.pem |
| 容器 | docker compose ps |
STATUS 为 Up (healthy) |
healthcheck 未定义,或 80/443 未映射 |
| 对外暴露端口 | nmap -p 80,443,3306 example.com |
仅 80、443 为 open | compose 里误写 3306:3306 |
第一层是跳转链路。据 RFC 7538,301 对 GET 请求安全,但会把 POST 降级为 GET;若你的 API 需要保留方法,应改用 308。用 -L 查看最终 URL,用 -v 提取跳转链路,避免出现 302 临时跳转或多跳:
# 1) 80 端口必须永久跳转到 https
curl -I http://example.com
# 期望首行:HTTP/1.1 301 Moved Permanently
# 期望响应头:Location: https://example.com/
# 2) 跟随跳转,确认最终落地页返回 200
curl -I -L http://example.com
# 期望末段:HTTP/2 200
# 3) 只提取状态码与 Location,快速确认链路
curl -v http://example.com 2>&1 | grep -E '301|Location'
# 4) 检查 HSTS(RFC 6797),max-age 建议 ≥ 31536000 秒
curl -sI https://example.com | grep -i strict-transport-security
第二层是证书本身。注意 openssl s_client 必须带 -servername,否则 SNI 缺失会取到默认站点证书,产生误判:
# 校验证书链与有效期,期望 Verify return code: 0 (ok)
openssl s_client -connect example.com:443 -servername example.com -showcerts &1
| grep -E 'Verify return code|subject=|issuer='
# 直接查容器内 Let's Encrypt 文件的有效期(路径按实际 volume 调整)
docker compose exec nginx openssl x509
-in /etc/letsencrypt/live/example.com/fullchain.pem -noout -dates -issuer
# 期望 notAfter 在未来 60 天以上,issuer 为 R11 或 ISRG Root X1(据 Let's Encrypt 文档)
第三层检查容器与对外暴露端口。docker compose config 会把变量插值后的最终 YAML 打印出来,是排查“我明明改了却没用”最快的手段:
docker compose config | grep -A4 'ports:' # 确认 80:80 / 443:443
docker compose ps # STATUS 应为 Up (healthy)
docker compose logs --tail=100 nginx | grep -iE 'emerg|[error]' # 期望无输出
ss -lntp | grep -E ':80|:443' # 宿主机监听确认
curl -I http://服务器IP:8080 # 期望 Connection refused 或 301
第四层查混合内容:页面仍引用 http:// 资源时,浏览器会显示锁但标记为“部分不安全”,HSTS 也救不了:
curl -s https://example.com | grep -io 'http://[^"'"'"' >]*' | sort -u | head
# 有输出即存在混合内容,需改成 // 或 https:// 相对协议引用
最后别忘了续期通道。据 Let’s Encrypt 文档,dry-run 只做模拟签发不消耗速率限制,是验证 webroot 与 ACME 挑战链路是否仍然可用的标准做法:
docker compose run --rm certbot renew --dry-run
# 期望输出:Congratulations, all simulated renewals succeeded
浏览器侧再补一次人工确认:DevTools → Security 面板应显示 Connection – secure,Network 面板按 http: 过滤应为空。这三层(命令行、容器、浏览器)互相独立,任一层异常都能定位到具体环节,而不是笼统地“HTTPS 好像没生效”。
多容器、Swarm 与 K8s Ingress 场景下还要注意什么?
多容器、Swarm 与 K8s Ingress 场景下,怎样避免有人用 IP:3000 绕过 HTTPS?
做 docker 强制https 时,最常见的绕过口不是 Nginx,而是 app 容器把端口发布到了宿主机。Compose/Swarm 中 app 只写 expose: ["3000"],不写 ports;仅入口 nginx 发布 80/443。Swarm 的 routing mesh 会把 ports 发布到每个节点,所以 app 更不能写 ports: ["3000:3000"]。这样 http://宿主机IP:3000 会直接 Connection refused,外部只能走 80→443。
services:
app:
image: myapp:1.0
expose: ["3000"] # 仅容器网络可见,不发布到宿主机
# 不要写 ports: ["3000:3000"]
nginx:
image: nginx:1.27
ports:
- "80:80" # 仅入口发布 80
- "443:443" # 仅入口发布 443
volumes:
- ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
- ./certs:/etc/nginx/certs:ro
# 验证:curl -I http://127.0.0.1:3000 应返回 Connection refused
K8s 里 ssl-redirect 默认是 true 吗? 据 ingress-nginx 文档,nginx.ingress.kubernetes.io/ssl-redirect 默认 true(仅当 Ingress 配置了 TLS),建议显式写 "true";force-ssl-redirect 默认 false。cert-manager 1.14+ 用 ClusterIssuer 签发,Ingress 的 tls.secretName 指向证书 Secret。
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata: {name: letsencrypt-prod}
spec:
acme:
server: https://acme-v02.api.letsencrypt.org/directory
privateKeySecretRef: {name: le-key}
solvers:
- http01: {ingress: {class: nginx}}
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: app
annotations:
nginx.ingress.kubernetes.io/ssl-redirect: "true"
spec:
ingressClassName: nginx
tls:
- hosts: ["example.com"]
secretName: example-tls # 由 cert-manager 写入
rules:
- host: example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service: {name: app, port: {number: 80}}
# 检查:kubectl describe ingress app
Traefik v3 只给 websecure 配 TLS 够吗? 不够。web 入口路由必须绑定 redirectScheme 中间件,websecure 绑定 tls.certResolver;否则 http 仍可明文访问。v3 CRD 组为 traefik.io/v1alpha1。
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata: {name: redirect-https}
spec:
redirectScheme: {scheme: https, permanent: true} # 308,保留方法
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: app-web}
spec:
entryPoints: [web]
routes:
- match: Host(`example.com`)
kind: Rule
middlewares: [{name: redirect-https}]
services: [{name: app, port: 80}]
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: app-websecure}
spec:
entryPoints: [websecure]
routes:
- match: Host(`example.com`)
kind: Rule
services: [{name: app, port: 80}]
tls: {certResolver: letsencrypt}
| 场景 | 强制跳转落点 | 常见坑 |
|---|---|---|
| Compose/Swarm | nginx 80 server return 301 https://$host$request_uri |
app 写了 ports: 3000:3000,或 Swarm 发布了端口 |
| ingress-nginx 1.10+ | ssl-redirect: "true" |
Ingress 无 TLS 或 Secret 不存在 |
| Traefik v3 | web 路由绑 redirectScheme |
只配 websecure TLS,web 未跳转 |
内网也要上 HSTS 吗?多域名证书怎么签? 据 RFC 6797,HSTS 只对域名生效,用 IP 访问无效;内网服务间通信不建议套公网 HSTS,改用 mTLS 或 service mesh,公网入口统一 301/308。灰度先 max-age=300,观察 24h 无混合内容后升 86400,最后 31536000;加 includeSubDomains/preload 前确认所有子域已 HTTPS。
# Nginx 灰度 HSTS:先 300 秒,确认无混合内容再逐级调大
add_header Strict-Transport-Security "max-age=300" always;
# 多域名 SAN 证书(Let's Encrypt 单证书最多 100 个域名)
certbot certonly --webroot -w /var/www/certbot
-d example.com -d www.example.com -d api.example.com
--email ops@example.com --agree-tos --no-eff-email
# 触发限流会报:too many certificates already issued for example.com
# 每注册域名每周 50 张,批量前先规划
灰度验证 docker 强制https 是否生效:Nginx 的 log_format 中加入 scheme=$scheme,确认 access_log 中非 https 请求为 0,并统计 301/308 跳转量;出现 ERR_TOO_MANY_REDIRECTS 时先查入口是否又回源到 80。
grep -v 'scheme=https' /var/log/nginx/access.log | wc -l # 应为 0
awk '$9==301' /var/log/nginx/access.log | wc -l # 301 跳转量
awk '$9==308' /var/log/nginx/access.log | wc -l # 308 跳转量
curl -sI http://example.com | head -n 1 # 301/308
curl -sI https://example.com | head -n 1 # 200
上线检查清单、回滚与监控怎么做?
上线前 10 分钟,按顺序跑完这 6 条命令,能挡掉 90% 的翻车
据 Let’s Encrypt 文档,http-01 校验失败最常见的原因是 80 端口被 301 到 HTTPS 却没放行 ACME 路径,或者安全组只开了 443。Docker 场景下建议把检查脚本固定下来,每次改配置都重跑:
# 1) DNS 必须 A/AAAA 都已生效,TTL 建议先设 300 便于回滚
dig +short A example.com @1.1.1.1
dig +short AAAA example.com @1.1.1.1
# 2) ACME 路径应返回 404(文件不存在),返回 403 说明被 WAF/规则拦了,certbot 会报 unauthorized
curl -sS -o /dev/null -w '%{http_code}n' http://example.com/.well-known/acme-challenge/probe
# 3) fullchain.pem 必须含 2 段证书(站点证书 + 中间证书),只有 1 段会触发
# "unable to get local issuer certificate" 类错误
grep -c 'BEGIN CERTIFICATE' /etc/letsencrypt/live/example.com/fullchain.pem
# 4) 跳转与转发头是否到位
curl -sSI http://example.com | head -n 3 # 期望 301 Location: https://
curl -sSI https://example.com | grep -i 'strict-transport-security' # HSTS 首轮 max-age=300
curl -sSI https://example.com | grep -i 'x-forwarded-proto' # 期望 https
# 5) 证书到期时间(可放进每日 cron)
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null
| openssl x509 -noout -subject -enddate
# 6) 健康检查不要只走 HTTP,否则强制跳转后容器被判不健康
curl -fsS http://127.0.0.1:8080/healthz # 容器内直连端口,绕过 Nginx
证书申请失败或 HSTS 需要回滚怎么办?把 return 301 https://$host$request_uri; 临时改成 return 302 并保留被注释掉的 80 server 块,302 不会被浏览器缓存,改完即刻生效;301 会被 Chrome/Firefox 长期缓存,用户端无法远程清除。HSTS 更严格——据 RFC 6797,浏览器一旦收到 Strict-Transport-Security 就会在 max-age 内强制 HTTPS,服务端无法撤销,所以首轮用 max-age=300,确认无误后再升到 31536000。回滚只能等过期。
监控:两个探针 + 一条证书告警
# blackbox.yml —— 分别验证「HTTP 必 301」与「HTTPS 必 200」
modules:
http_redirect:
prober: http
http:
follow_redirects: false # 关键:不跟随,才能看到原始 301
valid_status_codes: [301]
https_ok:
prober: http
http:
follow_redirects: true
valid_status_codes: [200]
# prometheus 告警规则:证书剩余 < 21 天
- alert: CertExpiringSoon
expr: (probe_ssl_earliest_cert_expiry - time()) / 86400 < 21
for: 1h
成本与方案怎么选?
| 方案 | 费用 | 续期方式 | 适用场景 |
|---|---|---|---|
| Let’s Encrypt + certbot 容器 | 0 元 | cron 自动,90 天一轮 | 绝大多数自建 Docker 栈 |
| 云 LB 托管证书 | 约 0.02 元/小时起 + 流量费 | 自动 | 不想自运维 ACME |
| 商业 DV/OV 证书 | 约 800–3000 元/年 | 手动或 API | 合规、审计要求 |
首次配置约 0.5–2 小时,续期自动化后每月维护通常小于 10 分钟。安全基线按 Mozilla SSL Configuration Generator 的 intermediate 档位:
ssl_protocols TLSv1.2 TLSv1.3; # 禁用 TLSv1.0/1.1
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
ssl_stapling on;
ssl_stapling_verify on;
resolver 127.0.0.11 valid=30s; # 缺这行 stapling 静默失效,error.log 报 "no resolver defined to resolve r3.o.lencr.org"
文档里必须写死版本号,否则半年后排查时镜像已漂移:nginx:1.26-alpine、certbot/certbot:v2.11.0、traefik:v3.0、caddy:2.8-alpine,并记录证书挂载路径、cron 时间(如 0 3 * * *)和回滚命令 docker compose up -d --force-recreate nginx。这份清单的目标只有一个:下次故障 5 分钟内定位到是 DNS、ACME 路径还是证书链的问题。
不能完成首次跳转,且 HTTP-01 证书续期会失败。浏览器直接访问 http://example.com 时没有 80 监听会连接拒绝,HSTS 也无法在首次访问前生效;建议保留 80 仅用于 ACME 与 301,或改用 DNS-01 并接受用户必须手动输入 https://。
301 在部分浏览器和客户端会改变请求方法,登录、支付、API 建议改用 308 保留方法。Nginx 写 return 308 https://$host$request_uri;,测试阶段先用 302 避免缓存;同时确认上游应用没有再次 301。
容器频繁增减、需要自动发现时选 Traefik v3,标签里配 redirectscheme 中间件即可;单机多站点、已有 Nginx 经验时选 Nginx 1.26 + certbot 更可控;小团队想少写配置选 Caddy 2.8。三者都能实现 301/308,差异主要在证书管理和动态发现。
先查 CDN 回源协议是否 HTTP、源站是否又 301 到 HTTPS,再查应用是否重复跳转。用 curl -I https://example.com 看 Location,Nginx 加 proxy_set_header X-Forwarded-Proto https;,Spring Boot 3.2 设 server.forward-headers-strategy=framework,Express 4.18 设 app.set('trust proxy', 1)。
用 certbot/certbot:v2.11.0 容器执行 certbot renew –quiet,cron 每天 03:17 跑一次,成功后 docker compose exec nginx nginx -s reload。先用 docker compose run –rm certbot renew –dry-run 验证;续期失败最常见原因是 80 端口被关闭或 ACME 路径被 301 拦截。
可以用于内网测试,但浏览器会报 NET::ERR_CERT_AUTHORITY_INVALID,curl 会报 unable to get local issuer certificate。生产建议用 Let's Encrypt 或商业证书;内部服务可把 CA 放到 /usr/local/share/ca-certificates 后执行 update-ca-certificates,并让客户端信任该 CA。
先从 max-age=300 测试 24 小时,确认无混合内容后升 86400,再升 31536000。加 includeSubDomains 前必须确认所有子域都有 HTTPS;preload 提交后撤销周期以月计,不建议一开始就加。
本文由 sslgood.com 安全团队基于生产环境实战经验撰写,关键结论均经过技术复核。