502 bad gateway connection refused

I'm having a problem with a project i'm working on. I'm using traefik as reverse proxy using PathPrefix in a docker compose with multiple .net 8 apis. I will share the docker compose file with just 1 api to be short:

version: '3.8'

services:
  traefik:
    image: traefik:v2.11
    restart: unless-stopped
    command:
      - --entrypoints.web.address=:80
      - --providers.docker=true
      - --providers.docker.exposedByDefault=false
      - --accesslog=true
      - --log.level=DEBUG
      - --api.insecure=true 
      - --api.dashboard=true 
      - --api.debug=true 
      - --providers.docker.network=web 
    ports:
      - 80:80
      - 8080:8080
    volumes:
      - /etc/localtime:/etc/localtime:ro
      - /var/run/docker.sock:/var/run/docker.sock:ro 
    labels:
      - traefik.enable=true
      - traefik.http.routers.api.service=api@internal 
    networks:
       web:


  api1:
    image: ${DOCKER_REGISTRY-}api1
    restart: always
    build:
      context: .
      dockerfile: api1/Dockerfile
    # ports:
    #   - 0.0.0.0:8090:8090
    labels:
      - traefik.enable=true
      - traefik.http.routers.api1.rule=Host(`localhost`) && PathPrefix(`/api1`)
      - traefik.http.routers.api1.service=api1@docker
      - traefik.http.routers.api1.entrypoints=web
      - traefik.http.services.api1.loadbalancer.server.port=8090
    networks:
       web:

networks:
  web:

I am able to access the dashboard when i use localhost:8080 and i can see my configuration. but the problem is when I try to access my api1 on "localhost/api1/swagger" i get "502 bad gateway connection refused".
The api swagger is already configured to route when using /api1/swagger and my api runs properly alone without the docker compose with traefik.
I'm fairly new to traefik, i'm using visual studio to debug and i'm running the apps on docker desktop locally for now.
Thanks is advance

Bad gateway usually happens when Traefik and target service are not connected to the same or multiple Docker networks.

The issue is probably this line:

--providers.docker.network=web

Either you

  • remove it (not needed with target service on single Docker network)
  • adapt it to the real Docker network name (which gets a prefix by compose)
  • add name: web to the compose network definition (to keep the name fixed)

Hello, thank you for your reply. I tried all ur suggestions still no luck.

Strange, check and compare to simple Traefik example (link).