Running Traefik in Docker
Traefik is a popular open source edge router and reverse proxy that makes deploying microservices easy. It integrates with Docker and automatically configures SSL certificates via Let’s Encrypt.
In this post, we’ll be installing and configuring Traefik on Docker using Docker Compose. We’ll also set up a sample website container and secure it with SSL using the integrated Let’s Encrypt support.
To make things more modular, we’ll split up the Traefik configuration and website container into separate Docker Compose files. We’ll also secure the Traefik web UI by routing it through Traefik itself.
Installing Traefik
First, we need to create a docker-compose.traefik.yml file that will define our Traefik service:
version: '3'
services:
traefik:
image: traefik:v2.2
command: --api.insecure=true --providers.docker --log
ports:
- "80:80"
- "443:443"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- traefik-public-certificates:/certificates
labels:
- "traefik.http.routers.traefik.rule=Host(`traefik.example.com`)"
- "traefik.http.routers.traefik.entrypoints=websecure"
- "traefik.http.routers.traefik.tls=true"
- "traefik.http.services.traefik.loadbalancer.server.port=8080"
volumes:
traefik-public-certificates:
networks:
- proxy
This exposes port 80 and 443, enables the API and logging, and configures a router and service for the Traefik web UI at traefik.example.com using SSL.
Let’s start it up:
docker-compose -f docker-compose.traefik.yml up -d
Traefik should now be up and running, with the web UI available at https://traefik.example.com.
Adding a Sample Website
Next, we’ll create a Docker Compose file to run a simple website container:
docker-compose.web.yml:
version: '3'
services:
web:
image: nginx:alpine
labels:
- "traefik.http.routers.web.rule=Host(`example.com`)"
- "traefik.http.routers.web.entrypoints=websecure"
- "traefik.http.routers.web.tls=true"
networks:
- proxy
networks:
proxy:
external: true
This attaches the web container to the proxy network, allowing Traefik to automatically pick it up.
Let’s start it up:
docker-compose -f docker-compose.web.yml up -d
Traefik will grab the SSL certificate for example.com and route traffic to the web container.
Conclusion
With just a few labels, we can easily add containers to Traefik without needing to reconfigure the proxy itself. This makes it easy to deploy new microservices and scale horizontally.
Securing the Traefik web UI behind its own proxy is a best practice that ensures outside clients can’t directly access the dashboard.
Let me know if you have any other questions!