DevOps
Traefik v3: Routing Multiple Docker Apps on One Server
Port collisions and manual nginx configs are the price of running multiple Docker apps on one server. Traefik v3 auto-discovers containers and routes each one cleanly using labels.
- Published
- Reading
- 8 min
- Author
- Fidelis Uwem Joseph
Series · Part 2 of 4Self-hosted Infrastructure
- Self-Hosted Dev Infrastructure with Docker Compose
- Traefik v3: Routing Multiple Docker Apps on One Server
- Traefik v3: Automatic Routing, TLS, and Middleware for Docker
- Docker on a VPS: UFW, Port Bindings, and SSH Tunnels
Running five Docker apps on one server creates an immediate problem: which port goes to which service, and how do you keep it from becoming a mess as the stack grows? The usual answer is Nginx with manually maintained config blocks. That works until a container restarts with a new IP and your proxy is pointing at nothing.
Traefik solves this by watching the Docker socket directly. When a container starts with the right labels, Traefik builds the route. When it stops, the route disappears. No config reload, no manual upstream blocks, no downtime.
This post covers a production-ready Traefik v3 setup with named entrypoints per service, a locked-down dashboard, and Docker-label-based routing. Every other post in this series builds on this foundation.
Assumed knowledge: Docker Compose basics, what a reverse proxy does.
Prerequisites
- Docker Engine 24+
- Docker Compose v2
- A Linux server (Ubuntu 22.04+ used throughout)
If you are running this on a public VPS, read Securing a Public-Facing Dev Stack alongside this post. Traefik opens ports, and you need to know which ones should be public before you start.
Background
Traefik has two config layers that behave very differently.
Static config (traefik.yml) loads once at startup and defines entrypoints, providers, and log levels. It cannot be hot-reloaded. Any change requires a Traefik restart.
Dynamic config is discovered continuously at runtime, from Docker labels, config files, or the API. Container changes are picked up immediately with no restart required.
The Docker provider watches the socket. When a container starts with traefik.enable=true, Traefik reads its labels and builds the route. When the container stops, the route disappears. You define your entrypoints once in the static config, then route each service by adding labels to its container.
Implementation
1. Define the shared Docker network
All services that Traefik needs to route to must share a network. Define it once here. External Compose stacks attach to it with external: true.
networks: infra_net: driver: bridge name: infra_net
volumes: traefik_logs:The explicit name: infra_net is required. Without it, Docker prefixes the name with the Compose project name and external references break.
2. Static configuration
This file is mounted into the Traefik container read-only. It does not change at runtime.
api: dashboard: true insecure: true
entryPoints: web: address: ":80" traefik: address: ":8080" ams-api: address: ":8001" ams-frontend: address: ":8002" hms-api: address: ":8003" hms-frontend: address: ":8004" mail-server: address: ":8005"
providers: docker: exposedByDefault: false network: infra_net
log: level: INFO
accessLog: {}3. Traefik service in Docker Compose
services: traefik: image: traefik:v3.2 container_name: traefik restart: unless-stopped ports: - "0.0.0.0:80:80" - "127.0.0.1:8080:8080" - "0.0.0.0:8001:8001" - "0.0.0.0:8002:8002" - "0.0.0.0:8003:8003" - "0.0.0.0:8004:8004" - "0.0.0.0:8005:8005" volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - ./traefik/traefik.yml:/etc/traefik/traefik.yml:ro - traefik_logs:/logs networks: - infra_net labels: - "traefik.enable=false"Two things worth noting here. The dashboard port 8080 binds to 127.0.0.1 only, so it is not reachable from the internet. Setting traefik.enable=false on Traefik’s own container prevents it from accidentally routing traffic to itself.
4. Routing a service with labels
Labels on a container are how you opt into routing. This routes the Mailpit web UI through the mail-server entrypoint:
mailpit: image: axllent/mailpit:latest networks: - infra_net labels: - "traefik.enable=true" - "traefik.http.routers.mailpit.rule=PathPrefix(`/`)" - "traefik.http.routers.mailpit.entrypoints=mail-server" - "traefik.http.services.mailpit.loadbalancer.server.port=8025"The three labels do exactly this: opt the container in, match all requests arriving on the mail-server entrypoint, and forward them to port 8025 inside the container. Traefik infers the container’s IP from the shared Docker network. You never specify an IP address directly.
5. Accessing the dashboard via SSH tunnel
The dashboard runs on port 8080, bound to 127.0.0.1. Forward it to your local machine over SSH:
ssh -L 8080:127.0.0.1:8080 user@your-serverOpen http://localhost:8080/dashboard/ in your browser. You can inspect every router, service, and middleware Traefik has discovered without touching any config files.
Testing
Bring the stack up:
docker compose up -dCheck that Traefik has discovered your routes:
curl -s http://localhost:8080/api/http/routers | jq '.[].name'"mailpit@docker""api@internal"Test a route end-to-end. This hits the mail-server entrypoint and should return a 200:
curl -I http://your-server:8005HTTP/1.1 200 OKConfirm the Docker provider is running:
curl -s http://localhost:8080/api/providers | jq 'keys'["docker"]Pitfalls
Production considerations
When you are ready to serve traffic on real domains, add certificatesResolvers to traefik.yml to enable Let’s Encrypt TLS. Traefik handles certificate renewal automatically. You add one config block in the static config and switch each router label from entrypoints=web to entrypoints=websecure.
For public routes that need rate limiting or authentication, Traefik middlewares handle both without any changes to your application code. The basicAuth middleware accepts a htpasswd string and adds HTTP basic auth to any router in a single label.
Enable structured access logs by replacing accessLog: {} with accessLog: { filePath: /logs/access.log }. This gives you a full request audit trail. When something breaks in production at an inconvenient hour, that log is usually the first place showing what changed.
If the Docker socket should not be accessible at all in your environment, switch to the file provider. Routes are no longer auto-discovered and you manage a dynamic config file manually, but the attack surface shrinks considerably.
Going deeper
Put a proxy in front of the Docker socket
The pitfall above is real: the Docker API has no read-only mode worth the name. :ro on the bind mount only stops the socket file from being replaced. Requests sent through it can still start containers, and a container that can start containers can mount the host filesystem. If Traefik is ever compromised, the socket is the path to root.
A socket proxy sits between Traefik and Docker and only forwards the API calls you allow. Traefik needs to list containers and watch events, nothing more:
socket-proxy: image: tecnativa/docker-socket-proxy:latest restart: unless-stopped environment: CONTAINERS: 1 # GET /containers/* EVENTS: 1 # GET /events (on by default) NETWORKS: 1 # network details for routing POST: 0 # no write operations at all volumes: - /var/run/docker.sock:/var/run/docker.sock:ro networks: - socket_net
traefik: # remove the docker.sock volume from traefik networks: - infra_net - socket_net
networks: socket_net: internal: true # no route to the outside worldproviders: docker: endpoint: "tcp://socket-proxy:2375" exposedByDefault: false network: infra_netOnly Traefik and the proxy are on socket_net, and internal: true gives that network no outbound access. App containers cannot reach the proxy at all.
A dashboard without insecure: true
insecure: true serves the dashboard on its own entrypoint with no authentication. Binding it to 127.0.0.1 makes that acceptable, but one mistaken port mapping makes it public. The secure mode routes the dashboard like any other service, so you can put authentication in front of it:
api: dashboard: true # insecure removedentryPoints: admin: address: ":8080" traefik: labels: - "traefik.enable=true" - "traefik.http.routers.dashboard.rule=PathPrefix(`/api`) || PathPrefix(`/dashboard`)" - "traefik.http.routers.dashboard.entrypoints=admin" - "traefik.http.routers.dashboard.service=api@internal" - "traefik.http.routers.dashboard.middlewares=dashboard-auth" - "traefik.http.middlewares.dashboard-auth.basicauth.users=${TRAEFIK_DASHBOARD_USERS}"Generate the user entry with htpasswd -nbB admin 'a-long-password'. In the .env file, double every $ in the hash ($$2y$$05$$...), otherwise Compose treats parts of the hash as variables. Keep the 127.0.0.1:8080 binding as well: authentication and a loopback binding protect against different mistakes.
Scale an app and let Traefik balance it
Traefik load balances across every running container that belongs to the same Compose service. You get horizontal scaling for free, with one catch: container_name must not be set, because Docker cannot start two containers with the same name.
docker compose up -d --scale api=3curl -s http://localhost:8080/api/http/services | jq '.[] | select(.name=="api@docker") | .loadBalancer.servers'The second command should list three server URLs. If the app keeps per-user state in memory, add sticky sessions so each user stays on one instance:
- "traefik.http.services.api.loadbalancer.sticky.cookie=true"A better long-term fix is to move that state into Redis so any instance can serve any request.
Route only to healthy containers
If a container defines a Docker health check, Traefik leaves it out of the load balancer until the check reports healthy. That is what makes rolling restarts graceful: a freshly started instance receives no traffic while it is still booting.
api: healthcheck: test: ["CMD", "curl", "-fsS", "http://localhost:8000/health"] interval: 10s timeout: 3s retries: 3 start_period: 20sThe flip side: a health check that never passes makes the route disappear completely, and requests get a 404 instead of an error from the app. If a route vanishes after adding a health check, run docker inspect --format '{{json .State.Health}}' <container> before looking at Traefik.
Stop repeating labels
Each app needs the same four or five labels with only the name and port changing. Compose extension fields and YAML anchors keep them consistent:
x-traefik: &traefik traefik.enable: "true" traefik.docker.network: infra_net
services: api: labels: <<: *traefik traefik.http.routers.ams-api.rule: PathPrefix(`/`) traefik.http.routers.ams-api.entrypoints: ams-api traefik.http.services.ams-api.loadbalancer.server.port: "8000"Labels written as a map (key: value) can be merged with <<:. Labels written as a list (- "key=value") cannot, so use the map form when you want anchors.
When you get a domain
One entrypoint per app is a good fit for a dev server reached by IP address. Once you have a domain, route by hostname instead: every app on ports 80 and 443, told apart by Host() rules, with automatic TLS. The entrypoint-per-app ports can then close. The production patterns post covers that setup.
Reading Traefik’s error codes
Most routing problems show up as one of three status codes, and each points somewhere different:
| Status | What it means | Where to look |
|---|---|---|
404 page not found (plain text) | No router matched the request | Router rule, entrypoint, traefik.enable, health status |
502 Bad Gateway | A router matched but Traefik could not reach the container | loadbalancer.server.port, shared network, app listening on 0.0.0.0 |
504 Gateway Timeout | The container accepted the connection but did not answer in time | App performance, long requests, timeouts |
A common 502 cause is an app that listens on 127.0.0.1 inside its container. Traefik connects over the Docker network, so the app must listen on 0.0.0.0 (for example uvicorn --host 0.0.0.0).
Wrapping up
Traefik v3’s Docker provider turns container labels into live routes with no restarts and no per-service config files. One entrypoint per service keeps your firewall rules clean and your routing unambiguous. This setup is the foundation the rest of this series builds on.
- Self-Hosted Dev Infrastructure with Docker Compose adds Postgres, Redis, MinIO, and Mailpit to this stack
- MinIO as a Self-Hosted S3 Backend
- Catching Emails with Mailpit and Traefik
- Full source: github.com/joseph-fidelis