Docker + Traefik in Production: The Complete Setup Guide
Why This Setup Exists
I run 10+ Docker Compose stacks on a single Hetzner VPS: personal sites, client projects, an ERP system, monitoring, analytics, and various APIs. Every one of them needs HTTPS, proper security headers, and the ability to deploy independently without touching the others.
Traefik makes this work. It sits in front of everything, handles SSL certificates automatically, and routes traffic based on domain names. Each stack is a self-contained docker-compose.yml that knows nothing about its neighbors.
Here is how I set it all up.
Traefik: The Single Entry Point
Every stack connects to one shared Docker network called proxy. Traefik watches the Docker socket for new containers and configures routing from their labels -- no config files to edit when you add a new site.
The Traefik stack itself is minimal:
# /opt/stacks/traefik/docker-compose.yml
services:
traefik:
image: traefik:v3.6
container_name: traefik
restart: unless-stopped
ports:
- "80:80"
- "443:443"
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
- ./acme.json:/acme.json
- ./traefik.yml:/etc/traefik/traefik.yml:ro
networks:
- proxy
networks:
proxy:
external: true
Create the network once: docker network create proxy. Every stack joins it.
The static config enables Let's Encrypt and the Docker provider:
# traefik.yml
entryPoints:
web:
address: ":80"
http:
redirections:
entryPoint:
to: websecure
scheme: https
websecure:
address: ":443"
certificatesResolvers:
letsencrypt:
acme:
email: your@email.com
storage: /acme.json
httpChallenge:
entryPoint: web
providers:
docker:
exposedByDefault: false
network: proxy
Setting exposedByDefault: false is important -- containers must explicitly opt in with traefik.enable=true.
Adding a Site With Automatic SSL
Each site stack declares its routing via labels. Here is what my personal site looks like:
services:
hoedl-co-web:
build: .
container_name: hoedl-co
restart: unless-stopped
ports:
- "127.0.0.1:3000:80"
networks:
- proxy
deploy:
resources:
limits:
cpus: '0.5'
memory: 256M
healthcheck:
test: ["CMD", "wget", "--quiet", "--tries=1",
"--spider", "http://127.0.0.1/"]
interval: 30s
timeout: 10s
retries: 3
labels:
- "traefik.enable=true"
- "traefik.http.routers.hoedl-co.rule=Host(`hoedl.co`)"
- "traefik.http.routers.hoedl-co.entrypoints=websecure"
- "traefik.http.routers.hoedl-co.tls.certresolver=letsencrypt"
- "traefik.http.services.hoedl-co.loadbalancer.server.port=80"
- "autoheal=true"
networks:
proxy:
external: true
Three labels handle everything: the domain, the entrypoint, and the cert resolver. Traefik requests and renews the Let's Encrypt certificate automatically.
Notice ports: "127.0.0.1:3000:80" -- this binds the port to localhost only. Traffic reaches the container through Traefik, not by hitting port 3000 directly. Without the 127.0.0.1 prefix, Docker bypasses iptables and exposes the port to the internet.
The Multi-Stage Dockerfile
Every static site uses the same two-stage build pattern: Node builds the assets, nginx serves them.
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
RUN rm /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
RUN chown -R nginx:nginx /usr/share/nginx/html && \
chmod -R 755 /usr/share/nginx/html
EXPOSE 80
HEALTHCHECK --interval=30s --timeout=3s \
CMD wget -qO- http://localhost:80/ || exit 1
CMD ["nginx", "-g", "daemon off;"]
The final image is ~25MB with no Node.js runtime, no node_modules, no source code. Only the compiled assets and nginx.
Security Headers in nginx
Traefik handles TLS termination, but each container sets its own security headers in nginx. This is the minimal set I put on every site:
server {
listen 80;
server_tokens off;
root /usr/share/nginx/html;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy
"strict-origin-when-cross-origin" always;
add_header Strict-Transport-Security
"max-age=63072000; includeSubDomains; preload" always;
add_header Permissions-Policy
"camera=(), microphone=(), geolocation=()" always;
add_header Content-Security-Policy
"default-src 'self'; script-src 'self';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
frame-ancestors 'self';" always;
# Block source maps in production
location ~* \.map$ { return 404; }
# Static assets: aggressive caching
location ~* \.(js|css|png|jpg|svg|woff2)$ {
expires 1y;
add_header Cache-Control "public, immutable" always;
}
# SPA fallback
location / {
try_files $uri $uri/ /index.html;
}
gzip on;
gzip_vary on;
gzip_comp_level 6;
gzip_min_length 256;
gzip_types text/plain text/css application/json
application/javascript image/svg+xml;
}
A few things worth calling out: HSTS with max-age=63072000 (two years) tells browsers to never use HTTP. The CSP blocks inline scripts by default -- adjust script-src per site if you need analytics or third-party scripts. And server_tokens off hides the nginx version from response headers.
Resource Limits and Health Checks
Every container gets CPU and memory limits. A static site does not need more than half a CPU and 256MB. Without limits, a single runaway container can starve the entire server.
deploy:
resources:
limits:
cpus: '0.5'
memory: 256M
Health checks let Docker know when a container is broken, not just running. Combined with the autoheal label and the willfarrell/autoheal container, unhealthy services restart automatically:
healthcheck:
test: ["CMD", "wget", "--quiet", "--tries=1",
"--spider", "http://127.0.0.1/"]
interval: 30s
timeout: 10s
retries: 3
labels:
- "autoheal=true"
I run autoheal as a sidecar in the Traefik stack. It watches all containers labeled autoheal=true and restarts any that fail their health check three times in a row.
CrowdSec: Automated DDoS and Brute-Force Protection
CrowdSec sits between Traefik and the internet, analyzing access logs in real time. When it detects attack patterns -- credential stuffing, path traversal, vulnerability scanning -- it bans the IP via the firewall bouncer.
The key detail: the bouncer operates on the DOCKER-USER iptables chain, which Docker checks before its own routing rules. This means banned IPs are blocked before they reach any container, but it never interferes with SSH access.
CrowdSec also shares threat intelligence with a community network. If an IP is attacking other servers, it gets preemptively banned on yours. I have seen it block thousands of automated scans before they even start probing my stacks.
Common Mistakes and Debugging
"Traefik doesn't see my container." Make sure the container is on the proxy network and has traefik.enable=true. Check with docker network inspect proxy.
"SSL certificate not issued." The HTTP challenge requires port 80 to be open and the DNS A record to point to your server. Check docker logs traefik for ACME errors. Also verify acme.json has chmod 600.
"Port is accessible without Traefik." You published the port without binding to localhost. Use 127.0.0.1:PORT:PORT, never just PORT:PORT.
"Container keeps restarting." Check docker logs <container> first. If the health check is wrong (checking the wrong port or path), the autoheal loop will restart it endlessly.
"Security headers missing on some routes." In nginx, add_header inside a location block overrides all server-level headers. You need to repeat them in every location block, or use an include file.
The Result
This setup has been running stable for months. Adding a new site takes about 10 minutes: write a Dockerfile, add Traefik labels, push to the repo, and the webhook triggers a rebuild. Traefik picks up the new container, requests the SSL certificate, and the site is live.
No manual certificate management. No nginx reverse proxy configs to edit. No port conflicts. Just self-contained stacks that deploy independently and fail independently.
The full infrastructure runs on a single Hetzner CPX32 (4 vCPU, 8GB RAM) with room to spare.