You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker+NGINX架构下FastAPI子域名路由异常问题求助

问题解决思路

核心问题定位

访问api.localhost却显示Flask页面,说明NGINX没有正确根据Host头匹配到对应的FastAPI服务,大概率是本地DNS解析未配置或NGINX配置格式错误导致的。

分步解决方案

1. 配置本地Hosts文件

首先确保api.localhost能解析到本地:

  • Windows:编辑C:\Windows\System32\drivers\etc\hosts,添加一行:
    127.0.0.1 api.localhost
    
  • Linux/macOS:编辑/etc/hosts,添加同样内容。
    这一步是让浏览器访问api.localhost时,发送正确的Host: api.localhost请求头,NGINX才能匹配到对应的server块。

2. 修正NGINX配置格式

你的NGINX配置包含了完整的http { ... }块,但默认的NGINX主配置文件已经包含了http上下文,嵌套会导致配置失效。修改后的配置应只保留两个server块:

server {
    listen 80;
    server_name localhost;

    location / {
        proxy_pass http://ux:9000;
    }
}

server {
    listen 80; 
    server_name api.localhost;

    location / {
        proxy_pass http://api:8000;
    }
}

3. 确保NGINX正确加载配置

检查你的NGINX Dockerfile,确保配置文件被复制到正确位置。比如./nginx/Dockerfile内容应为:

FROM nginx:alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf

这样会覆盖默认的配置文件,让NGINX加载你的路由规则。

4. 验证配置并重启服务

  • 进入NGINX容器检查配置语法:
    docker exec -it nginx sh
    nginx -t
    
    输出test is successful说明配置无语法错误。
  • 查看访问日志确认请求头:
    cat /var/log/nginx/access.log
    
    检查api.localhost请求的Host字段是否为api.localhost。
  • 重启所有服务:
    docker-compose down && docker-compose up --build
    

额外说明

你设置的Flasksubdomain_matching=False参数不影响当前问题,因为请求根本没被NGINX转发到Flask,是路由匹配环节出了问题,无需关注该参数。

内容的提问来源于stack exchange,提问作者Danylo Klymenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 10:43:10