Redirecting HTTP to HTTPS with Traefik v2
In this article, we will set up Traefik v2 to automatically redirect HTTP requests to HTTPS for a sample service. This configuration is done entirely within a Docker Compose file, making it easy to manage and deploy.
Prerequisites
- Docker and Docker Compose installed on your machine.
- Basic understanding of Docker and Traefik.
Docker Compose Configuration
Below is a sample docker-compose.yml file that sets up Traefik and a simple service called whoami. The configuration ensures that any requests made to http://whoami.mysite.com are redirected to https://whoami.mysite.com.
version: "3.3"
services:
traefik:
image: "traefik:v2.0"
container_name: "traefik"
command:
- "--log.level=DEBUG"
- "--api.insecure=true"
- "--providers.docker=true"
- "--providers.docker.exposedbydefault=false"
- "--entrypoints.web.address=:80"
- "--entrypoints.web-secure.address=:443"
- "--certificatesresolvers.myhttpchallenge.acme.httpchallenge=true"
- "--certificatesresolvers.myhttpchallenge.acme.httpchallenge.entrypoint=web-secure"
- "--certificatesresolvers.myhttpchallenge.acme.email=me@mail.com"
- "--certificatesresolvers.myhttpchallenge.acme.storage=/letsencrypt/acme.json"
labels:
- "traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https"
ports:
- "80:80"
- "443:443"
- "8080:8080"
volumes:
- "./letsencrypt:/letsencrypt"
- "/var/run/docker.sock:/var/run/docker.sock:ro"
whoami:
image: "containous/whoami"
container_name: "whoami"
labels:
- "traefik.enable=true"
- "traefik.http.routers.whoami.rule=Host(`whoami.mysite.com`)
- "traefik.http.routers.whoami.entrypoints=web"
- "traefik.http.routers.whoami.middlewares=redirect-to-https@docker"
- "traefik.http.routers.whoami-secured.rule=Host(`whoami.mysite.com`)
- "traefik.http.routers.whoami-secured.entrypoints=web-secure"
- "traefik.http.routers.whoami-secured.tls=true"
- "traefik.http.routers.whoami-secured.tls.certresolver=myhttpchallenge"
Explanation of Key Components
- Entry Points: We define two entry points:
webfor HTTP (port 80) andweb-securefor HTTPS (port 443). - Certificates Resolver: This configuration uses Let's Encrypt to automatically generate SSL certificates.
- Middleware: The
redirect-to-httpsmiddleware is applied to thewhoamiservice to ensure that any HTTP requests are redirected to HTTPS.
Running the Configuration
To start the services, run the following command in the directory containing your docker-compose.yml:
docker-compose up -d
After the services are up, you can test the redirection by navigating to http://whoami.mysite.com. You should be automatically redirected to https://whoami.mysite.com.
Conclusion
This setup provides a straightforward way to enforce HTTPS for your services using Traefik v2 and Docker Compose. Adjust the configuration as necessary for your specific use case.