How traefik work with more than one docker network

Hello, i have 2 backend service (one of them use db - web-db and second not - web) and 1 database (postgresql) all of them are in the docker containers. But i don't want to share database to net, so i want web-db to use database docker container address. I create external network db-service-network and add it to web-db and also add it to traefik compose file. It works well, but now if i want to use web i need to modify it's compose file and add db-service-network even if it didn't use it. If i don't add it traefik will not give access to my web.

web-db file:

version: '3.8'

services:
  web:
    build: .
    command: bash -c 'while !</dev/tcp/db/5432; do sleep 1; done; uvicorn app.main:app --host 0.0.0.0 --port 80'
    volumes:
      - .:/app
    expose:
      - 80
    environment:
      - DATABASE_URL=postgresql://fastapi_traefik:fastapi_traefik@db:5432/fastapi_traefik
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.fastapi.rule=Host(`fastapi.localhost`) && PathPrefix(`/test/db`)"
    networks:
      - db-service-network
      - traefik

networks:
  db-service-network:
    external: true
  traefik:
    external: true

traefik file:



services:

  traefik:
    image: "traefik:v2.11"
    container_name: "traefik"
    command:
      #- "--log.level=DEBUG"
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=false"
      - "--entrypoints.web.address=:80"
      - "--entrypoints.websecure.address=:443"
    ports:
      - "80:80"
      - "443:443"
      - "8081:8080"
    volumes:
      - "./traefik.dev.toml:/etc/traefik/traefik.toml"
      - "/var/run/docker.sock:/var/run/docker.sock:ro"
    networks:
      - db-service-network

networks:
  default:
    name: traefik
  db-service-network:
    external: true

web file:


version: '3.8'

services:
  web:
    build: .
    command: bash -c 'uvicorn app.main:app --host 0.0.0.0 --port 80'
    volumes:
      - .:/app
    expose:
      - 80
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.fastapi.rule=Host(`fastapi.localhost`) && PathPrefix(`/test/web`)"
    networks:
      - db-service-network
      - traefik

networks:
  traefik:
    external: true
  db-service-network:
    external: true

If i don't add db-service-network traefik will show gateway timeout

You need to define docker.network to tell Traefik which Docker network to use to forward requests. It can be global on providers.docker for all target services or individual per service in dynamic config (file or labels).

Note that Docker compose usually prefixed a Docker network with the project name, so use name: to fix this in network definition, see simple Traefik example.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.