Using traefik v2.0+ docker image, you can simply use docker-compose
and define your environment variables in .env
file. Then use labels like this below example.
Example
Uses File provider to add self-signed TLS certificates for localhost using traefik CLI command:
--providers.file.filename=/etc/traefik/certs.toml
.env
file in local:
# Environment variables for docker-compose.yml
LOG_LEVEL=DEBUG
NETWORK=net
## dashboard configs
DASHBOARD_HOST=app.localhost
CONFIG_PATH=./config
CERT_PATH=./certs
.env
file in production:
# Environment variables for docker-compose.yml
# LOG_LEVEL=INFO
LOG_LEVEL=ERROR
NETWORK=net
## dashboard configs
DASHBOARD_HOST=realname.com
CONFIG_PATH=./config
CERT_PATH=./certs
docker-compose.yml:
version: "3.5"
services:
traefik:
# Setting container_name disables running multinple instances of this service
container_name: traefik
image: traefik:v2.1
command:
- --entrypoints.web.address=:80
- --entrypoints.websecure.address=:443
- --log.level=${LOG_LEVEL}
- --providers.docker
- --providers.docker.exposedbydefault=false
- --providers.file.filename=/etc/traefik/certs.toml
- --api
ports:
- "80:80"
- "443:443"
networks:
- net
volumes:
- "${CERT_PATH}:/certs"
- "${CONFIG_PATH}:/etc/traefik"
- "/var/run/docker.sock:/var/run/docker.sock:ro"
labels:
# set this lebel to `false` and the rest is history
traefik.enable: true
# middleware redirect
traefik.http.middlewares.redirect-to-https.redirectscheme.scheme: https
# redirection HTTP to HTTPS
traefik.http.routers.http_catchall.rule: hostregexp(`{host:.+}`)
traefik.http.routers.http_catchall.entrypoints: web
traefik.http.routers.http_catchall.middlewares: redirect-to-https
# dashboard
traefik.http.routers.traefik.rule: Host(`${DASHBOARD_HOST}`)
traefik.http.routers.traefik.entrypoints: websecure
traefik.http.routers.traefik.service: api@internal
traefik.http.routers.traefik.tls: true
networks:
net:
external: false
name: ${NETWORK}
config/certs.toml:
[tls.stores.default.defaultCertificate]
certFile = "/certs/cert.crt"
keyFile = "/certs/cert.key"
certs/cert.crt:
-----BEGIN CERTIFICATE-----
<THE CERTIFICATE STRING>
-----END CERTIFICATE-----
certs/cert.key:
-----BEGIN RSA PRIVATE KEY-----
<THE RSA PRIVATE KEY STRING>
-----END RSA PRIVATE KEY-----
docker-compose
will replace all the variables like ${DASHBOARD_HOST}
with the values defined in .env
file.
Then, you can validate your config using: docker-compose config
Run using: docker-compose up -d
-d
flag is for detached mode, runs containers in the background
Source Files:
You can refer to this repository on github to find an elaborate version of this example, on how to setup traefik v2
using docker-compose
for self-signed or to automatically acquire Let's Encrypt wildcard certificates.