Search code examples
dockertraefik

Why am I unable to route to my API backend with Traefik


I had two container frontend (nginx :80) and backend (nodejs :3000). I'm trying to redirect all path to my frontend : localhost/* to my frontend Except one path to my backend API : localhost/v1/* to my backend

I secure my database container (mongodb) by allowing only communication with my backend

Here is my docker-compose.yml (I'm only using this)

version: '3'

services:
  traefik:
    image: traefik:v2.3
    container_name: traefik
    command:
      - --api.insecure=true
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --entrypoints.web.address=:80
    ports:
      - "8080:8080"
      - "443:443"
      - "80:80"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro

  frontend:
    image: registry.gitlab.com/test/frontend
    container_name: frontend
    build:
      context: ../frontend/.
    labels:
      - traefik.enable=true
      - traefik.http.routers.frontend.rule=PathPrefix(`/`)
      - traefik.http.routers.frontend.entrypoints=web    
    networks:
      - traefik-network

  backend:
    image: registry.gitlab.com/test/backend
    container_name: backend
    build:
      context: ../backend/.
    labels:
      - traefik.enable=true
      - traefik.http.routers.backend.rule=PathPrefix(`/v1`)
      - traefik.http.routers.backend.service=backend
      - traefik.http.routers.backend.entrypoints=web
      - traefik.http.services.backend.loadbalancer.server.port=3000
    command: yarn start
    environment:
      - MONGODB_URL=mongodb://mongodb:27017/backend
    depends_on:
      - mongodb
    volumes:
      - ../backend/.:/usr/src/backend
    networks:
      - traefik-network
      - backend-network

  mongodb:
    image: mongo:4.2.1-bionic
    container_name: mongodb
    ports:
      - 27017:27017
    volumes:
      - dbdata:/data/db
    networks:
      - backend-network

volumes:
  dbdata:

networks:
  backend-network:
  traefik-network:

The problem is...

If the frontend (backend and traefik too) is turned on

  • the paths to localhost/* work (this is what I want),
  • but the paths to localhost/v1/* don't work (Problem here!).

If the frontend is turned off but traefik and backend is turned on

  • the paths to localhost/* don't work (of course, that's right),
  • but the paths to localhost/v1/* work (of course, this is what I want).

I've tried a lot of solutions but nothing seems to work the way I want it to. What did I misunderstand?

Thanks for helping, Have a nice day


Solution

  • I added this label to my containers

    traefik.docker.network=traefik-network

    It works fine now