Если вы когда-либо управляли несколькими Docker-контейнерами с веб-сервисами, то знаете, как быстро маршрутизация трафика превращается в головную боль. Каждый новый сервис — это правка конфига Nginx, перезагрузка и риск что-то сломать. Traefik решает эту проблему кардинально: он автоматически обнаруживает новые контейнеры и настраивает маршруты на лету, без перезагрузок и ручного вмешательства. Кроме того, он умеет сам выдавать SSL-сертификаты через Let’s Encrypt и предоставляет удобный дашборд для мониторинга.
В этой статье мы развернём Traefik в Docker, подключим к нему несколько сервисов, настроим HTTPS через вилкард сертификат и посмотрим, как это всё работает в реальной связке.
Структура проекта #
# cd /data/docker-projects/traefik
# tree
├── docker-compose.yml
├── dynamic.yml
└── tls
├── fullchain.crt
└── privkey.key
Запуск Traefik #
docker-compose.yml
services:
traefik:
image: traefik:v3.7
container_name: traefik
restart: unless-stopped
command:
# Dashboard
- --api.dashboard=true
- --api.insecure=true
# Docker provider
- --providers.docker=true
- --providers.docker.exposedbydefault=false
# Dynamic config
- --providers.file.filename=/etc/traefik/dynamic.yml
- --providers.file.watch=true
# Entrypoints
- --entrypoints.web.address=:80
- --entrypoints.websecure.address=:443
# Logs
- --log.level=INFO
ports:
- "80:80"
- "443:443"
- "8080:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
- ./dynamic.yml:/etc/traefik/dynamic.yml:ro
- ./tls:/etc/traefik/tls:ro
networks:
- traefik-proxy
networks:
traefik-proxy:
name: traefik-proxy
Сертификат для Traefik #
tls:
certificates:
- certFile: /etc/traefik/tls/fullchain.crt
keyFile: /etc/traefik/tls/privkey.key
stores:
default:
defaultCertificate:
certFile: /etc/traefik/tls/fullchain.crt
keyFile: /etc/traefik/tls/privkey.key
Запуск проксируемых сервисов #
Сделаем один docker-compose.yml, где будут 4 nginx-контейнера, каждый демонстрирует свой вариант работы с Traefik:
- nginx-http-only → только HTTP :80
- nginx-https-only → только HTTPS :443
- nginx-redirect → HTTP → HTTPS redirect
- nginx-both → HTTP + HTTPS без redirect
Предполагается, что Traefik уже запущен отдельно и есть сеть traefik-proxy.
docker-compose.yml
services:
##############################################
# 1. Только HTTP
# http://http-only.example.com
##############################################
nginx-http-only:
image: nginx:latest
container_name: nginx-http-only
networks:
- traefik-proxy
labels:
- "traefik.enable=true"
# HTTP router
- "traefik.http.routers.http-only.rule=Host(`http-only.example.com`)"
- "traefik.http.routers.http-only.entrypoints=web"
# Backend
- "traefik.http.services.http-only.loadbalancer.server.port=80"
##############################################
# 2. Только HTTPS
# https://https-only.example.com
##############################################
nginx-https-only:
image: nginx:latest
container_name: nginx-https-only
networks:
- traefik-proxy
labels:
- "traefik.enable=true"
# HTTPS router
- "traefik.http.routers.https-only.rule=Host(`https-only.example.com`)"
- "traefik.http.routers.https-only.entrypoints=websecure"
- "traefik.http.routers.https-only.tls=true"
# Backend
- "traefik.http.services.https-only.loadbalancer.server.port=80"
##############################################
# 3. HTTP -> HTTPS redirect
# http://redirect.example.com
# |
# v
# https://redirect.example.com
##############################################
nginx-redirect:
image: nginx:latest
container_name: nginx-redirect
networks:
- traefik-proxy
labels:
- "traefik.enable=true"
# Middleware
- "traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https"
# HTTP router
- "traefik.http.routers.redirect-http.rule=Host(`redirect.example.com`)"
- "traefik.http.routers.redirect-http.entrypoints=web"
- "traefik.http.routers.redirect-http.middlewares=redirect-to-https"
# HTTPS router
- "traefik.http.routers.redirect-https.rule=Host(`redirect.example.com`)"
- "traefik.http.routers.redirect-https.entrypoints=websecure"
- "traefik.http.routers.redirect-https.tls=true"
# Backend
- "traefik.http.services.redirect.loadbalancer.server.port=80"
##############################################
# 4. HTTP + HTTPS без redirect
# http://both.example.com
# https://both.example.com
##############################################
nginx-both:
image: nginx:latest
container_name: nginx-both
networks:
- traefik-proxy
labels:
- "traefik.enable=true"
# HTTP
- "traefik.http.routers.both-http.rule=Host(`both.example.com`)"
- "traefik.http.routers.both-http.entrypoints=web"
# HTTPS
- "traefik.http.routers.both-https.rule=Host(`both.example.com`)"
- "traefik.http.routers.both-https.entrypoints=websecure"
- "traefik.http.routers.both-https.tls=true"
# Backend
- "traefik.http.services.both.loadbalancer.server.port=80"
networks:
traefik-proxy:
name: traefik-proxy
Запуск и проверка #
docker compose up -d
docker compose config
docker compose logs -f
В Traefik Dashboard http://IP:8080/dashboard появятся 5 router’ов (точнее 7, потому что redirect имеет два router’а):
- http-only
- https-only
- redirect-http
- redirect-https
- both-http
- both-https