DevOps
Traefik v3: Automatic Routing, TLS, and Middleware for Docker
Nginx breaks every time a container restarts with a new IP. Traefik watches the Docker socket and rebuilds routes automatically, TLS included. Complete production setup from scratch.
- Published
- Reading
- 12 min
- Author
- Fidelis Uwem Joseph
Series · Part 3 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 multiple Docker apps behind Nginx means writing upstream blocks, running nginx -s reload, and doing it again every time a container restarts with a new IP. Nginx is a file-driven proxy built for static infrastructure. Docker is the opposite: containers die, restart, scale, and get replaced continuously. The mismatch is not subtle, it creates a permanent maintenance loop.
Traefik eliminates that loop. It watches the Docker socket directly. When a container starts with the right labels, Traefik builds the route. When the container stops, the route disappears. No config files per service, no reload commands, no manual certificate management.
This post covers Traefik’s architecture, a direct comparison with Nginx and Nginx Proxy Manager, and a complete production setup: static config, Docker Compose, label-based routing, Let’s Encrypt TLS, HTTP-to-HTTPS redirect, path-based routing, and dashboard access via SSH tunnel.
Assumed knowledge: Docker Compose basics, what a reverse proxy does.
Prerequisites
- Docker Engine 24+
- Docker Compose v2
- A domain with DNS you control (required for Let’s Encrypt TLS)
- A Linux server with ports 80 and 443 accessible
The examples use infra_net as the shared Docker network, consistent with the setup in Self-Hosted Dev Infrastructure with Docker Compose.
Background
How Traefik works
Traefik is an edge router, it sits in front of your containers and decides which one handles each incoming request. It was designed specifically for environments where services are added, removed, and restarted constantly. That assumption drives every design decision: the config model, the discovery mechanism, the TLS handling.
The architecture has two distinct layers.
Static config loads once at startup. It defines entrypoints (the ports Traefik listens on), providers (where Traefik discovers services), and certificate resolvers. It cannot be hot-reloaded. Any change requires a Traefik restart.
Dynamic config is discovered continuously at runtime. The Docker provider watches the socket. When a container starts with traefik.enable=true, Traefik reads its labels and builds the route immediately. When the container stops, the route disappears. No restart, no config edits, no downtime.
This separation is what makes Traefik operationally useful for Docker. Your routing table updates itself.
Why Nginx falls short in Docker environments
Nginx stores routing config in files. Every upstream server, every virtual host, every proxy_pass block is a .conf file you write manually and reload manually. That model works when your server topology changes rarely. It breaks down in Docker environments.
When a container restarts, Docker assigns a new internal IP. Nginx still holds the old upstream IP. Requests fail with “connection refused” until you edit the config and run nginx -s reload. At ten containers, this becomes a constant maintenance burden.
The deeper issue is that Nginx has no Docker integration whatsoever. It has no concept of containers. You are the synchronization layer between Docker’s state and Nginx’s config and that synchronization is always one container restart away from being wrong.
Nginx Proxy Manager extends Nginx with a GUI but does not change its underlying limitations. NPM generates static Nginx config files behind the scenes. Clicking “Save” writes a .conf and reloads Nginx. The routing table still does not update automatically when containers restart or scale. The GUI itself becomes a single point of failure: if the NPM container is down, you cannot manage routes. Every route lives in a SQLite database inside the GUI container not version-controlled, not scriptable.
The operational difference is concrete:
| Capability | Nginx / NPM | Traefik |
|---|---|---|
| Route discovery on container start | Manual config + reload | Automatic from labels |
| Route removal on container stop | Manual config edit | Automatic |
| TLS certificate management | Certbot + cron | Built-in, auto-renewing |
| Config version control | Possible with .conf files | Labels live in Compose file |
| Reusable middleware | Separate blocks per service | Named, referenced by label |
| Zero-downtime routing changes | No (requires reload) | Yes |
| Automation API | None natively | Full HTTP API |
Nginx is an excellent proxy for static workloads. The problem is fit, not quality.
Implementation
1. Define the shared Docker network
All containers Traefik routes to must share a network. Define it once here. External app stacks reference it with external: true.
networks: infra_net: driver: bridge name: infra_net
volumes: letsencrypt: 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 read once at startup. Mount it read-only.
api: dashboard: true
entryPoints: web: address: ":80" websecure: address: ":443" traefik: address: ":8080"
providers: docker: exposedByDefault: false network: infra_net
certificatesResolvers: le: acme: email: you@example.com storage: /letsencrypt/acme.json httpChallenge: entryPoint: web
log: level: INFO
accessLog: filePath: /logs/access.logexposedByDefault: false is the single most important setting in this file. Without it, every container on infra_net gets a public route, including your databases and internal services. Always set this to false and opt services in explicitly with traefik.enable=true.
The httpChallenge ACME resolver uses port 80 to verify domain ownership. Traefik handles the HTTP-01 challenge automatically, fetches the certificate, and renews it before expiry. No certbot, no cron job.
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" - "0.0.0.0:443:443" - "127.0.0.1:8080:8080" volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - ./traefik/traefik.yml:/etc/traefik/traefik.yml:ro - letsencrypt:/letsencrypt - traefik_logs:/logs networks: - infra_net labels: - "traefik.enable=false"Three things to note:
traefik.enable=falseon the Traefik container itself prevents Traefik from creating a self-referential route.- The Docker socket is mounted
:ro(read-only). Traefik can read container metadata but cannot issue Docker write commands. - Dashboard port
8080binds to127.0.0.1only, not reachable from outside the host.
4. Routing a service with labels
Labels on a container are the routing config. This routes a backend API to api.example.com over HTTPS with an auto-issued certificate:
api: image: your-api-image:latest container_name: api restart: unless-stopped networks: - infra_net labels: - "traefik.enable=true" - "traefik.http.routers.api.rule=Host(`api.example.com`)" - "traefik.http.routers.api.entrypoints=websecure" - "traefik.http.routers.api.tls=true" - "traefik.http.routers.api.tls.certresolver=le" - "traefik.http.services.api.loadbalancer.server.port=8000"What each label does:
traefik.enable=trueopt this container into Traefik routingrouters.api.rulematch incoming requests by Host headerrouters.api.entrypoints=websecurelisten on port 443routers.api.tls=trueterminate TLS on this routerrouters.api.tls.certresolver=lerequest a cert from the Let’s Encrypt resolverservices.api.loadbalancer.server.port=8000forward traffic to port 8000 inside the container
Traefik infers the container’s IP from the shared Docker network. You never specify an IP address anywhere.
When this container starts, the route appears in the dashboard within seconds. When it stops, the route disappears. No config edit, no reload.
5. HTTP to HTTPS redirect
Every service needs two routers: one on websecure for real traffic and one on web that redirects to HTTPS.
labels: - "traefik.enable=true"
# HTTPS router - "traefik.http.routers.api.rule=Host(`api.example.com`)" - "traefik.http.routers.api.entrypoints=websecure" - "traefik.http.routers.api.tls=true" - "traefik.http.routers.api.tls.certresolver=le" - "traefik.http.services.api.loadbalancer.server.port=8000"
# HTTP redirect router - "traefik.http.routers.api-http.rule=Host(`api.example.com`)" - "traefik.http.routers.api-http.entrypoints=web" - "traefik.http.routers.api-http.middlewares=redirect-https"
# Redirect middleware definition - "traefik.http.middlewares.redirect-https.redirectscheme.scheme=https" - "traefik.http.middlewares.redirect-https.redirectscheme.permanent=true"6. Path-based routing
For services reachable at a path rather than a subdomain, use PathPrefix:
labels: - "traefik.enable=true" - "traefik.http.routers.docs.rule=Host(`example.com`) && PathPrefix(`/docs`)" - "traefik.http.routers.docs.entrypoints=websecure" - "traefik.http.routers.docs.tls=true" - "traefik.http.routers.docs.tls.certresolver=le" - "traefik.http.services.docs.loadbalancer.server.port=8080"7. Accessing the dashboard via SSH tunnel
The dashboard is 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, middleware, and certificate Traefik has discovered, no config files involved.
Testing
Bring the stack up:
docker compose up -dConfirm Traefik has loaded the Docker provider:
curl -s http://localhost:8080/api/providers | jq 'keys'["docker"]List all routers Traefik has built:
curl -s http://localhost:8080/api/http/routers | jq '.[].name'"api@docker""api-http@docker"Test the HTTPS route end-to-end:
curl -I https://api.example.comHTTP/2 200server: traefikVerify the HTTP-to-HTTPS redirect:
curl -I http://api.example.comHTTP/1.1 301 Moved PermanentlyLocation: https://api.example.com/Confirm the TLS certificate is valid:
curl -v https://api.example.com 2>&1 | grep "SSL certificate"SSL certificate verify ok.Verify acme.json has correct permissions inside the container. Let’s Encrypt will not write to it otherwise:
docker exec traefik ls -la /letsencrypt/acme.json-rw------- 1 root root ... acme.jsonIf permissions are wrong, Traefik logs a warning at startup and the ACME resolver fails silently on the first certificate request.
Pitfalls
Production considerations
Use Let’s Encrypt staging during initial setup. Rate limit violations on the production endpoint can block certificate issuance for your domain for up to a week. Verify the full ACME flow on staging, then switch.
Back up acme.json off the server. This file contains your private keys and issued certificates. If the volume is lost, Traefik requests new certificates on next startup but your previous certificates are unrecoverable. Store encrypted backups outside the server, automated on a schedule.
Ship access logs to an aggregator. Set accessLog.filePath in the static config. The default format is Common Log Format. When something breaks at 3AM, the access log is usually the first place showing what changed. Logs left on disk fill the volume and are unavailable if the container is down.
Enable Prometheus metrics. Add metrics: { prometheus: {} } to the static config. The /metrics endpoint at http://localhost:8080/metrics exposes request counts, latency histograms, and certificate expiry timestamps. Alert on certificate expiry at 30 days gives enough runway to debug renewal failures before the cert actually expires.
Move middleware to a file provider for multi-engineer environments. Labels are per-service. A dynamic.yml file-defined secure-headers middleware can be referenced by every router with one label and updated in one place. Inline middleware definitions in labels do not scale past a handful of services.
Going deeper
Redirect to HTTPS once, at the entrypoint
Step 5 adds a second router to every service just to redirect HTTP to HTTPS. Traefik v3 can do this for every service at once, in the static configuration:
entryPoints: web: address: ":80" http: redirections: entryPoint: to: websecure scheme: https websecure: address: ":443" http: tls: certResolver: leEvery request on port 80 is now redirected, whether or not a router exists for it. The api-http routers and the redirect-https middleware can be deleted from every Compose file. Setting certResolver on the websecure entrypoint also means routers no longer need their own tls and tls.certresolver labels. A service now needs only its rule, entrypoint and port.
The ACME HTTP challenge still works with the redirect in place: Traefik answers /.well-known/acme-challenge/ requests itself before the redirect applies.
One middleware chain for every public router
The tip in step 5 suggests moving middlewares into a file. Here is a chain worth sharing across every public service: security headers, rate limiting and compression.
http: middlewares: secure-headers: headers: stsSeconds: 31536000 stsIncludeSubdomains: true frameDeny: true contentTypeNosniff: true referrerPolicy: strict-origin-when-cross-origin rate-limit: rateLimit: average: 50 burst: 100 compress: compress: {} public: chain: middlewares: [secure-headers, rate-limit, compress]providers: file: filename: /etc/traefik/dynamic.yml watch: true - "traefik.http.routers.api.middlewares=public@file"The @file suffix tells a Docker-defined router to look the middleware up in the file provider. With watch: true, editing dynamic.yml takes effect without a restart, unlike the static config. Turn on stsSeconds only once HTTPS works on every subdomain: browsers remember HSTS for a year and will refuse plain HTTP to those hosts.
Wildcard certificates with the DNS challenge
The HTTP challenge needs port 80 reachable from the internet and issues one certificate per hostname. The DNS challenge proves ownership by creating a TXT record through your DNS provider’s API instead. It works for servers behind a firewall and it can issue wildcard certificates, so new subdomains need no new certificate request.
certificatesResolvers: le-dns: acme: email: you@example.com storage: /letsencrypt/acme.json # caServer: https://acme-staging-v02.api.letsencrypt.org/directory # while testing dnsChallenge: provider: cloudflare resolvers: ["1.1.1.1:53", "8.8.8.8:53"] traefik: environment: CF_DNS_API_TOKEN: ${CF_DNS_API_TOKEN} # token scoped to Zone:DNS:Edit for one zone labels: - "traefik.http.routers.api.tls.domains[0].main=example.com" - "traefik.http.routers.api.tls.domains[0].sans=*.example.com"Scope the API token to editing DNS on one zone only. Anyone with this token can change your DNS records, so it deserves the same care as the private keys in acme.json.
Real client IPs behind Cloudflare or a load balancer
When Traefik sits behind a CDN or a cloud load balancer, every request appears to come from the proxy’s IP address. Access logs show the wrong clients, and the rate limiter above treats all your users as one, throttling everybody at once. Tell Traefik which upstream proxies to trust, so it uses the X-Forwarded-For header they set:
entryPoints: websecure: address: ":443" forwardedHeaders: trustedIPs: - "173.245.48.0/20" # Cloudflare ranges, see cloudflare.com/ips - "103.21.244.0/22" # ...Only list proxies you actually use. Trusting X-Forwarded-For from everyone lets any client claim any IP address, which defeats both the logs and the rate limit.
To make sure nobody bypasses the CDN by connecting to the server’s IP directly, add an ipAllowList middleware with the same ranges to public routers, or restrict ports 80 and 443 to those ranges at the firewall.
Access logs you can search
The default access log is Common Log Format, written for every request. JSON is easier to search and ship, and filters keep the volume manageable:
accessLog: filePath: /logs/access.log format: json bufferingSize: 100 filters: statusCodes: ["400-599"] minDuration: 500ms fields: headers: defaultMode: drop names: User-Agent: keepWith filters set, Traefik writes a request only if it failed or took longer than 500 ms, which is usually what you search the log for anyway. Dropping headers by default keeps cookies and authorisation headers out of the log files.
Traefik does not rotate its log file. Use logrotate on the host with copytruncate, or send USR1 to the Traefik process after rotating, which makes it reopen the file.
Alert before certificates expire
Traefik renews certificates 30 days before they expire. Renewal can still fail silently: a changed DNS token, a firewall rule blocking port 80, or rate limits. With the Prometheus metrics from the production section enabled, alert on the expiry timestamp rather than finding out from users:
- alert: TLSCertificateExpiringSoon expr: (traefik_tls_certs_not_after - time()) / 86400 < 14 for: 1h annotations: summary: "Certificate for {{ $labels.cn }} expires in under 14 days"Fourteen days leaves two weeks after automatic renewal should have happened to fix whatever stopped it.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Browser shows “TRAEFIK DEFAULT CERT” | No certificate issued for that host yet, or ACME failed | Check Traefik logs for acme, test with the staging CA |
| Redirect loop | Upstream proxy terminates TLS and talks HTTP to Traefik | Trust the proxy’s forwarded headers, or use full TLS to the origin |
middleware "public@docker" does not exist | Missing @file suffix | Reference file middlewares as name@file |
| Every user rate-limited together | All requests appear to come from the CDN | Set forwardedHeaders.trustedIPs |
| DNS challenge times out | Propagation slow or token lacks permission | Set resolvers, check token scope |
Wrapping up
Traefik turns Docker labels into live routes with no config reload, no certificate management scripts, and no per-service proxy config files. The comparison with Nginx is not about raw performance. Nginx is faster for static file serving. It is about operational fit. Nginx was built for stable upstream servers and infrequent config changes. Traefik was built for environments where containers restart, scale, and get replaced continuously. The right tool depends entirely on which world your infrastructure lives in.
The next layer to harden is network security: which ports should be public, how to lock down internal services, and how Docker’s iptables rules interact with UFW.