首页 > 解决方案 > 使用 Traefik 和 Docker Compose 的错误网关

问题描述

我正在尝试在 docker compose 上部署一个 React + FastApi + Postgres 应用程序,并使用 Traefik 作为反向代理。我遇到了 Bad Gateway 错误的问题。在本地运行我的 FastAPI 在端口 8888 上运行它并公开/docs查看 api 文档的路径。我希望最终让应用程序example.local与可用的文档一起运行example.local/api/docs。我docker-compose.yaml的如下(大致基于这个):

version: '3.8'

services:
  proxy:
    image: traefik:v2.4
    networks:
      - web
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    ports:
      - '80:80'
      - '8080:8080'
      - '443:443'
    command:
      - --providers.docker
      - --api.insecure=true
      - --providers.docker.exposedbydefault=false
      - --providers.docker.network=web
      - --entrypoints.web.address=:80
    labels:
      - traefik.enable=true
      - traefik.http.routers.example-proxy-http.rule=Host(`example.local`)
      - traefik.http.routers.example-proxy-http.entrypoints=web
      - traefik.http.services.example-proxy.loadbalancer.server.port=80

  backend:
    build:
      context: ./backend
      dockerfile: Dockerfile
    command: python app/main.py
    volumes:
      - ./backend/app:/app
    env_file:
      - .env
    networks:
      - web
      - backend
    labels:
      - traefik.enable=true
      - traefik.http.routers.example-backend-http.rule=PathPrefix(`api/docs`)
      - traefik.http.routers.example-backend-http.entrypoints=web
      - traefik.http.services.example-backend.loadbalancer.server.port=8888

networks:
  web:
    external: true
  backend:
    external: false

我已添加127.0.0.1 example.local到我的/etc/hosts文件中。

从周围阅读看来,Bad Gateway 错误往往是由于 traefik 和相关服务不在同一网络上,或者 traefik 将流量路由到服务容器上的错误端口。但是,如果我ports: - '8888:8888'在后端服务中设置,我可以从中访问文档,localhost:8888/docs所以我很确定 8888 是后端负载均衡器的正确端口。从我可以看到 traefik 和后端服务也在同一个网络上,我已将其设置为默认的 traefik 网络--providers.docker.network=web。有趣的是,如果我localhost/api/docs在浏览器中访问,我会收到来自 FastAPI 的页面。所以这可能是我的 traefik http 路由器标签的问题?我对 traefik 和代理很陌生,所以非常感谢任何帮助或指导,谢谢!

更新

如果我通过添加指定后端的主机

- traefik.http.routers.infilmation-backend-http.rule=Host(`example.local`) && PathPrefix(`/docs`)

到后端服务标签,然后访问example.local/docs从 FastApi 提供页面。所以我想我的问题是为这个应用程序设置主机的最佳方式是什么?有没有办法可以为所有服务指定默认主机,然后任何PathPrefix规则都与该主机相关?

标签: docker-composereverse-proxytraefik

解决方案


推荐阅读