Traefik
A modern HTTP reverse proxy and load balancer that simplifies microservice deployment, with automatic service discovery and SSL certificate management
Alternatives
Tech stack
No tech stack added yet. Sign in to suggest some
Traefik is a modern HTTP reverse proxy and load balancer designed to simplify the deployment of microservices and containerized applications. It supports automatic service discovery, dynamic configuration, and automatic SSL certificate management, making it an ideal choice for cloud-native architectures.
Key Features
Automatic Service Discovery
- Docker integration: Automatically discovers and configures Docker containers
- Kubernetes support: Native Kubernetes Ingress controller
- Consul/Etcd/Zookeeper: Supports a variety of service registries
- File configuration: Supports static file configuration
- API configuration: Configure routes dynamically through the HTTP API
Automatic SSL Management
- Let's Encrypt integration: Automatically requests and renews SSL certificates
- Wildcard certificates: Supports wildcard domain certificates
- Multiple CA support: Works with multiple certificate authorities
- ACME protocol: Full ACME protocol support
- Certificate storage: Flexible certificate storage options
Load Balancing
- Multiple algorithms: Supports round robin, least connections, weighted algorithms, and more
- Health checks: Active and passive health checks
- Circuit breaker: A circuit-breaking mechanism that prevents cascading failures
- Retry mechanism: Smart retries when requests fail
- Sticky sessions: Supports session persistence
Middleware System
- Authentication middleware: Basic Auth, Digest Auth, Forward Auth
- Rate limiting middleware: Request rate limits and concurrency limits
- Redirect middleware: HTTP to HTTPS redirection
- Compression middleware: Automatic content compression
- CORS middleware: Cross-origin resource sharing configuration
- Custom middleware: Supports developing your own middleware
Technical Architecture
Core Components
- EntryPoints: Define the ports Traefik listens on
- Routers: Analyze requests and decide how to handle them
- Services: Define how to reach the actual services
- Middlewares: Modify requests and responses
- Providers: Discover services and configuration information
Supported Protocols
- HTTP/HTTPS: Standard web protocols
- HTTP/2: High-performance HTTP protocol
- TCP/UDP: Raw TCP and UDP proxying
- gRPC: Support for the high-performance RPC framework
- WebSocket: Real-time communication protocol
Deployment Configuration
Basic Docker Compose Configuration
version: '3.8'
services:
traefik:
image: traefik:v3.0
container_name: traefik
restart: unless-stopped
command:
# Docker configuration
- --providers.docker=true
- --providers.docker.exposedbydefault=false
# Entry point configuration
- --entrypoints.web.address=:80
- --entrypoints.websecure.address=:443
# Let's Encrypt configuration
- [email protected]
- --certificatesresolvers.letsencrypt.acme.storage=/letsencrypt/acme.json
- --certificatesresolvers.letsencrypt.acme.httpchallenge.entrypoint=web
# API and dashboard
- --api.dashboard=true
- --api.insecure=false
# Logging configuration
- --log.level=INFO
- --accesslog=true
ports:
- "80:80"
- "443:443"
- "8080:8080" # Dashboard port
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
- ./letsencrypt:/letsencrypt
- ./config:/etc/traefik
labels:
# Dashboard configuration
- "traefik.enable=true"
- "traefik.http.routers.dashboard.rule=Host(`traefik.example.com`)"
- "traefik.http.routers.dashboard.tls=true"
- "traefik.http.routers.dashboard.tls.certresolver=letsencrypt"
- "traefik.http.routers.dashboard.service=api@internal"
# Dashboard authentication
- "traefik.http.routers.dashboard.middlewares=dashboard-auth"
- "traefik.http.middlewares.dashboard-auth.basicauth.users=admin:$$2y$$10$$..."
# HTTPS redirect
- "traefik.http.routers.web-redirect.rule=HostRegexp(`{any:.*}`)"
- "traefik.http.routers.web-redirect.entrypoints=web"
- "traefik.http.routers.web-redirect.middlewares=web-redirect"
- "traefik.http.middlewares.web-redirect.redirectscheme.scheme=https"
- "traefik.http.middlewares.web-redirect.redirectscheme.permanent=true"
# Example application
whoami:
image: traefik/whoami
container_name: whoami
labels:
- "traefik.enable=true"
- "traefik.http.routers.whoami.rule=Host(`whoami.example.com`)"
- "traefik.http.routers.whoami.entrypoints=websecure"
- "traefik.http.routers.whoami.tls=true"
- "traefik.http.routers.whoami.tls.certresolver=letsencrypt"
Static Configuration File (traefik.yml)
# Entry point configuration
entryPoints:
web:
address: ":80"
http:
redirections:
entrypoint:
to: websecure
scheme: https
permanent: true
websecure:
address: ":443"
# Certificate resolver configuration
certificatesResolvers:
letsencrypt:
acme:
email: [email protected]
storage: /letsencrypt/acme.json
httpChallenge:
entryPoint: web
# DNS challenge configuration (Cloudflare example)
letsencrypt-dns:
acme:
email: [email protected]
storage: /letsencrypt/acme-dns.json
dnsChallenge:
provider: cloudflare
delayBeforeCheck: 30s
resolvers:
- "1.1.1.1:53"
- "8.8.8.8:53"
# Provider configuration
providers:
docker:
endpoint: "unix:///var/run/docker.sock"
exposedByDefault: false
network: traefik
file:
directory: /etc/traefik/dynamic
watch: true
# API and dashboard
api:
dashboard: true
insecure: false
# Logging configuration
log:
level: INFO
filePath: "/var/log/traefik/traefik.log"
accessLog:
filePath: "/var/log/traefik/access.log"
# Metrics configuration
metrics:
prometheus:
addEntryPointsLabels: true
addServicesLabels: true
# Global configuration
global:
checkNewVersion: false
sendAnonymousUsage: false
Dynamic Configuration Example
# Middleware configuration
http:
middlewares:
# Authentication middleware
auth:
basicAuth:
users:
- "admin:$2y$10$..."
# Rate limiting middleware
rateLimit:
rateLimit:
burst: 100
average: 50
# Security headers middleware
securityHeaders:
headers:
customRequestHeaders:
X-Forwarded-Proto: "https"
customResponseHeaders:
X-Frame-Options: "SAMEORIGIN"
X-Content-Type-Options: "nosniff"
sslRedirect: true
sslHost: "example.com"
sslForceHost: true
stsSeconds: 31536000
stsIncludeSubdomains: true
stsPreload: true
# CORS middleware
cors:
cors:
accessControlAllowMethods:
- GET
- OPTIONS
- PUT
- POST
accessControlAllowOriginList:
- "https://example.com"
accessControlMaxAge: 100
addVaryHeader: true
# Router configuration
routers:
api:
rule: "Host(`traefik.example.com`)"
tls:
certResolver: letsencrypt
middlewares:
- auth
- securityHeaders
service: api@internal
# Service configuration
services:
backend:
loadBalancer:
servers:
- url: "http://192.168.1.100:8080"
- url: "http://192.168.1.101:8080"
healthCheck:
path: "/health"
interval: "30s"
timeout: "3s"
# TCP routing configuration
tcp:
routers:
ssh:
rule: "HostSNI(`*`)"
entryPoints:
- ssh
service: ssh-service
services:
ssh-service:
loadBalancer:
servers:
- address: "192.168.1.100:22"
Advanced Features
Kubernetes Integration
apiVersion: v1
kind: Service
metadata:
name: traefik-service
spec:
selector:
app: traefik
ports:
- protocol: TCP
port: 80
name: web
- protocol: TCP
port: 443
name: websecure
- protocol: TCP
port: 8080
name: admin
type: LoadBalancer
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: traefik-deployment
spec:
replicas: 2
selector:
matchLabels:
app: traefik
template:
metadata:
labels:
app: traefik
spec:
containers:
- name: traefik
image: traefik:v3.0
args:
- --providers.kubernetescrd
- --entrypoints.web.address=:80
- --entrypoints.websecure.address=:443
ports:
- name: web
containerPort: 80
- name: websecure
containerPort: 443
- name: admin
containerPort: 8080
Service Mesh Integration
# Consul Connect configuration
providers:
consulCatalog:
endpoints:
- "consul:8500"
rootKey: "traefik"
connectAware: true
connectByDefault: true
# Jaeger distributed tracing
tracing:
jaeger:
samplingServerURL: "http://jaeger:14268/api/sampling"
localAgentHostPort: "jaeger:6831"
Plugin System
# Plugin configuration
experimental:
plugins:
geoblock:
moduleName: "github.com/PascalMinder/geoblock"
version: "v0.2.7"
# Plugin usage
http:
middlewares:
geoblock:
plugin:
geoblock:
silentStartUp: false
allowLocalRequests: true
logLocalRequests: false
logAllowedRequests: false
api: "https://get.geojs.io/v1/ip/country/{ip}"
allowedCountries:
- "US"
- "CN"
Monitoring and Logging
Prometheus Metrics
# Prometheus configuration
metrics:
prometheus:
addEntryPointsLabels: true
addServicesLabels: true
addMiddlewaresLabels: true
addRoutersLabels: true
buckets:
- 0.1
- 0.3
- 1.2
- 5.0
# Grafana dashboard
# Import the official dashboard ID: 4475
Structured Logging
log:
level: INFO
format: json
filePath: "/var/log/traefik/traefik.log"
accessLog:
format: json
filePath: "/var/log/traefik/access.log"
bufferingSize: 100
filters:
statusCodes:
- "400-499"
- "500-599"
retryAttempts: true
minDuration: "10ms"
fields:
defaultMode: keep
names:
ClientUsername: drop
headers:
defaultMode: keep
names:
User-Agent: redact
Authorization: drop
Content-Type: keep
Performance Optimization
Connection Configuration
# Connection pool configuration
serversTransport:
insecureSkipVerify: false
maxIdleConnsPerHost: 200
dialTimeout: "30s"
responseHeaderTimeout: "0s"
idleConnTimeout: "90s"
disableHTTP2: false
# Entry point configuration
entryPoints:
websecure:
address: ":443"
transport:
lifeCycle:
requestAcceptGraceTimeout: "10s"
graceTimeOut: "10s"
proxyProtocol:
trustedIPs:
- "127.0.0.1/32"
- "192.168.1.0/24"
Cache Configuration
http:
middlewares:
cache:
plugin:
traefik-cache:
ttl: "300s"
vary:
- "Accept-Encoding"
- "Authorization"
Security Configuration
TLS Security
tls:
options:
default:
minVersion: "VersionTLS12"
cipherSuites:
- "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"
- "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305"
- "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
sniStrict: true
stores:
default:
defaultCertificate:
certFile: "/etc/traefik/certs/default.crt"
keyFile: "/etc/traefik/certs/default.key"
Access Control
http:
middlewares:
ipWhitelist:
ipWhiteList:
sourceRange:
- "127.0.0.1/32"
- "192.168.1.0/24"
- "172.16.0.0/12"
forwardAuth:
forwardAuth:
address: "http://authelia:9091/api/verify?rd=https://authelia.example.com"
trustForwardHeader: true
authResponseHeaders:
- "Remote-User"
- "Remote-Name"
- "Remote-Groups"
Troubleshooting
Common Issues
-
Certificate request fails
- Check your DNS configuration
- Verify that port 80 is reachable
- Confirm that the email address is valid
-
Service discovery fails
- Check your Docker label configuration
- Verify network connectivity
- Confirm that Traefik has access to the Docker socket
-
Load balancing problems
- Check the health status of the backend services
- Verify the load balancing algorithm configuration
- Confirm that the service ports are correct
Debugging Tips
# Enable debug logging
--log.level=DEBUG
# Check the configuration
traefik version --format=json
# View routing information
curl -s "http://localhost:8080/api/http/routers" | jq
# Health check
curl -s "http://localhost:8080/ping"
Use Cases
Microservice Architecture
- API gateway: A unified entry point for services
- Service discovery: Automatically discovers new service instances
- Load balancing: Intelligent traffic distribution
- Circuit breaking: Prevents cascading failures
Containerized Deployment
- Docker integration: Seamless Docker support
- Kubernetes native: Full Kubernetes integration
- Multi-environment support: Development, testing, and production environments
Modernizing Legacy Applications
- Hybrid deployment: Old and new applications coexist
- Incremental migration: Smooth application migration
- SSL termination: Unified SSL management
Advantages
Compared with Traditional Reverse Proxies
- ✅ Automatic service discovery, no manual configuration needed
- ✅ Built-in SSL certificate management
- ✅ Modern API and dashboard
- ✅ Rich middleware ecosystem
Compared with Cloud Load Balancers
- ✅ Fully open source, no vendor lock-in
- ✅ Self-hosted, with complete control over your data
- ✅ Extensible with custom functionality
- ✅ No usage limits or fees
Traefik is an ideal choice for modern application architectures, especially for those who need a reverse proxy solution that is automated, scalable, and easy to manage. Its powerful feature set and cloud-native design make it a perfect companion for microservices and containerized applications.
Discover more
Algernon
Small self-contained pure-Go web server with Lua, Markdown, HTTP/2, QUIC, Redis and PostgreSQL support.
Caddy
Powerful, enterprise-ready, open source web server with automatic HTTPS.
Varnish
Web application accelerator/caching HTTP reverse proxy.
Zoraxy
General purpose HTTP reverse proxy and forwarding tool.
go-doxy
Lightweight, simple, and performant reverse proxy with WebUI, Docker integration, automatic shutdown/startup for container based on traffic.
Apache HTTP Server
Secure, efficient and extensible server that provides HTTP services in sync with the current HTTP standards.