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

Docker环境下Traefik搭配FastAPI时无法解析api.localhost的问题求助

Docker环境下Traefik搭配FastAPI时无法解析api.localhost的问题求助

我正在尝试用Docker部署FastAPI应用,并用Traefik做反向代理来处理请求路由。但目前遇到一个问题:api.localhost域名无法被正确解析,导致无法访问API。

我的目标

  • FastAPI运行在独立容器中,由Traefik负责将请求路由到它
  • 通过api.localhost就能访问FastAPI服务

遇到的错误

当我用Invoke-WebRequest或者浏览器访问http://api.localhost/时,会收到这个错误:

Invoke-WebRequest: The remote name could not be resolved: 'api.localhost'

FastAPI应用代码

我的FastAPI代码很简单,只有一个基础的状态接口:

@app.get("/")
def get_status():
    return {"status": "running"}

Docker Compose配置

这是我的docker-compose.yml内容:

version: "3.10"

services:
  test_api:
    build:
      context: ./test_api
      dockerfile: Dockerfile
    env_file:
      - .env
    ports:
      - "3000:3000"
    networks:
      - "traefik-internal"
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.api.rule=Host(`api.localhost`)"
      - "traefik.http.routers.api.entrypoints=web"

  traefik:
    image: traefik:latest
    command:
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--entrypoints.web.address=:80"
    ports:
      - "80:80"
      - "8080:8080"
    volumes:
      # 让Traefik能监听Docker事件
      - /var/run/docker.sock:/var/run/docker.sock
    networks:
      - "traefik-internal"

networks:
  traefik-internal:
    name: "traefik-internal"

我已经尝试过的操作

  • 确认Traefik容器正常运行,并且已经监听了80端口(配置了--entrypoints.web.address=:80)
  • 验证test_api容器正常运行,FastAPI应用在容器内部的3000端口可以访问
  • 打开Traefik仪表盘(http://localhost:8080),能看到api.localhost对应的路由规则已经存在

我的疑问

为什么通过Traefik路由访问api.localhost不行?是不是请求被什么拦截了?如果去掉Traefik,直接访问localhost:3000/是可以正常访问FastAPI的。

希望各位能给我一些思路,谢谢!

备注:内容来源于stack exchange,提问作者Rens

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 15:58:04