如何将子域名重定向到Docker容器对应端口(Cloudflare环境)
解决方案
方案一:Nginx反向代理 + Cloudflare DNS解析
如果Cloudflare Tunnel尝试失败,这个传统反向代理方案是稳定替代选项,步骤如下:
配置Cloudflare DNS记录
- 登录Cloudflare后台,找到域名
example.com - 添加两条A记录:
- 主机名填
vault,指向服务器公网IP,Cloudflare代理状态设为橙色(开启代理) - 主机名填
dash,指向服务器公网IP,Cloudflare代理状态设为橙色(开启代理)
- 主机名填
- 调整Cloudflare SSL/TLS模式:如果已有域名SSL证书,设为完全(Full)或严格(Full strict);暂未申请证书的话,先开**灵活(Flexible)**过渡,后续补证书。
- 登录Cloudflare后台,找到域名
部署Nginx反向代理
- 安装Nginx:
apt install nginx(Debian/Ubuntu)或yum install nginx(CentOS/RHEL) - 在
/etc/nginx/sites-available/目录下创建两个站点配置文件:vault.example.com.conf:server { listen 80; server_name vault.example.com; # 强制HTTP跳转到HTTPS return 301 https://$host$request_uri; } server { listen 443 ssl; server_name vault.example.com; # 填入Cloudflare Origin证书或自有SSL证书路径 ssl_certificate /path/to/your-cert.pem; ssl_certificate_key /path/to/your-key.pem; location / { proxy_pass http://localhost: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; } }dash.example.com.conf:server { listen 80; server_name dash.example.com; return 301 https://$host$request_uri; } server { listen 443 ssl; server_name dash.example.com; ssl_certificate /path/to/your-cert.pem; ssl_certificate_key /path/to/your-key.pem; location / { proxy_pass http://localhost:9090; 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; } }
- 启用配置文件:
ln -s /etc/nginx/sites-available/vault.example.com.conf /etc/nginx/sites-enabled/,同理执行dash配置文件的软链接 - 验证配置并重启Nginx:
nginx -t,无报错则执行systemctl restart nginx
- 安装Nginx:
防火墙端口放行
- 开放80、443端口:
ufw allow 80/tcp、ufw allow 443/tcp(Debian/Ubuntu);CentOS/RHEL用firewall-cmd --add-port=80/tcp --permanent、firewall-cmd --add-port=443/tcp --permanent后重载防火墙 - 确保Docker容器端口仅绑定
localhost或服务器内网IP,避免直接暴露公网绕开Cloudflare
- 开放80、443端口:
方案二:排查修复Cloudflare Tunnel配置
如果仍想使用Cloudflare Tunnel,按以下步骤排查问题:
确认Cloudflared客户端状态
- 检查系统服务状态:
systemctl status cloudflared,确保处于active运行状态 - 若用Docker运行cloudflared,查看容器日志定位错误:
docker logs [cloudflared容器名]
- 检查系统服务状态:
重新配置Tunnel路由
- 登录Cloudflare Zero Trust后台,找到目标Tunnel
- 添加两条公共主机名路由:
- 主机名填
vault.example.com,服务类型选HTTP,URL填http://localhost:8080;若容器和cloudflared在同一Docker网络,可直接填容器名+端口(如http://vaultwarden:8080) - 主机名填
dash.example.com,服务类型选HTTP,URL填http://localhost:9090;同一Docker网络下用容器名+端口
- 主机名填
- 若使用本地配置文件,确保包含对应路由规则:
tunnel: [你的Tunnel ID] credentials-file: /root/.cloudflared/[你的Tunnel ID].json ingress: - hostname: vault.example.com service: http://localhost:8080 - hostname: dash.example.com service: http://localhost:9090 - service: http_status:404 - 重启cloudflared:
systemctl restart cloudflared或重启对应Docker容器
调整SSL/TLS模式
- 将Cloudflare SSL/TLS模式设为完全(Full),适配Tunnel的加密链路
内容的提问来源于stack exchange,提问作者Ava
相关产品推荐
相关产品推荐

