Skip to content
Guides 6 Connection Type: 1 views

Traefik

Learn how Traefik simplifies reverse proxy and load balancing for Docker and Kubernetes, offering automatic service discovery and SSL management.

Traefik is an open-source Edge Router that automatically discovers and configures routes to your services by integrating directly with orchestrators like Docker and Kubernetes, acting as a dynamic reverse proxy and load balancer.

Core Concepts

Traefik operates on a dynamic configuration model, eliminating the need for manual file updates and service restarts when backend services change. This real-time adaptability is achieved through several interconnected components.

Providers

Providers are the connectors that allow Traefik to interact with your infrastructure. They monitor the underlying orchestrator's API for changes, such as new containers, services, or deployments.
Common providers include:
* Docker: Monitors Docker daemon events and container labels.
* Kubernetes: Monitors Kubernetes API for Ingress, IngressRoute, Service, and Endpoint resources.
* File: Reads configuration from static YAML or TOML files.
* Consul, etcd, ZooKeeper: Integrates with key-value stores for dynamic configuration.

Routing Configuration

Traefik processes incoming requests through a defined routing flow:

  • EntryPoints: These are network listeners that define the ports Traefik listens on (e.g., web on port 80, websecure on port 443).
  • Routers: Routers analyze incoming requests based on defined rules (e.g., Host(), PathPrefix(), Headers()). If a request matches a router's rule, it is forwarded. Routers also specify which EntryPoints they listen on and can apply Middlewares.
  • Middlewares: Middlewares are components that can modify requests before they reach the service or modify responses before they are sent back to the client. They can be chained together.
  • Services: Services define how to reach the actual backend application instances. A service typically points to one or more IP addresses and ports of your application. Traefik can load balance requests across multiple instances of a service.

The flow is: Request -> EntryPoint -> Router -> Middleware(s) -> Service -> Backend Application.

Key Features

Automatic Service Discovery

Traefik integrates directly with orchestrators like Docker and Kubernetes. It automatically discovers services by reading metadata (e.g., Docker labels, Kubernetes annotations, or Custom Resources) and dynamically updates its routing configuration without requiring any manual intervention or restarts. This eliminates the need for maintaining separate proxy configuration files.

SSL/TLS Termination

Traefik offers built-in support for SSL/TLS termination. It can automatically provision and renew certificates using Let's Encrypt via ACME (Automatic Certificate Management Environment) protocol, supporting HTTP-01, TLS-ALPN-01, and DNS-01 challenges. Custom certificates can also be configured.

Load Balancing

Traefik acts as a load balancer, distributing incoming traffic across multiple instances of a service.
Available load balancing strategies include:
* Round Robin: Distributes requests sequentially to each server.
* Weighted Round Robin: Allows assigning weights to servers to control traffic distribution.
* Sticky Sessions: Ensures requests from a specific client are always routed to the same server.

Middlewares

Middlewares provide a flexible way to modify requests or responses. They can be applied to specific routers or globally.
Examples of common middlewares include:
* Authentication: Basic authentication (BasicAuth), Digest authentication.
* Rate Limiting: Controls the number of requests a client can make within a specified time.
* Header Manipulation: Adding, removing, or modifying request/response headers.
* Redirects: HTTP to HTTPS redirection, permanent redirects.
* IP Whitelisting/Blacklisting: Restricting access based on client IP addresses.

Dashboard

Traefik includes a web-based dashboard that provides a real-time overview of the configured routers, services, and middlewares. It allows administrators to inspect the active configuration and monitor traffic.

Traefik with Docker

Integrating Traefik with Docker involves running Traefik as a container and allowing it to access the Docker daemon socket. Service configuration is typically managed via Docker labels on application containers.

Example docker-compose.yml Setup

The following example demonstrates a docker-compose.yml file for setting up Traefik and a sample whoami application.

version: '3.8'

services:
  traefik:
    image: traefik:v2.10
    command:
      - --api.dashboard=true
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false # Only expose services with traefik.enable=true
      - --entrypoints.web.address=:80
      - --entrypoints.websecure.address=:443
      - --certificatesresolvers.myresolver.acme.tlschallenge=true # For Let's Encrypt
      - --certificatesresolvers.myresolver.acme.email=your-email@example.com
      - --certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json # Persistent storage for certs
    ports:
      - "80:80"
      - "443:443"
      - "8080:8080" # Expose Traefik Dashboard
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock:ro" # Mount Docker socket for provider access
      - "./letsencrypt:/letsencrypt" # Persistent storage for ACME certificates
    labels:
      # Enable Traefik for the dashboard service itself
      - "traefik.enable=true"
      # Router for the Traefik dashboard
      - "traefik.http.routers.traefik-dashboard.rule=Host(`traefik.yourdomain.com`)"
      - "traefik.http.routers.traefik-dashboard.entrypoints=websecure"
      - "traefik.http.routers.traefik-dashboard.service=api@internal" # Internal Traefik API service
      - "traefik.http.routers.traefik-dashboard.tls.certresolver=myresolver"
      # Basic authentication middleware for the dashboard (replace with actual htpasswd hash)
      - "traefik.http.routers.traefik-dashboard.middlewares=dashboard-auth@docker"
      - "traefik.http.middlewares.dashboard-auth.basicauth.users=user:$$apr1$$YOUR_HTPASSWD_HASH"
    networks:
      - web

  whoami:
    image: traefik/whoami
    labels:
      - "traefik.enable=true" # Enable Traefik for this service
      - "traefik.http.routers.whoami.rule=Host(`whoami.yourdomain.com`)" # Define routing rule
      - "traefik.http.routers.whoami.entrypoints=websecure" # Listen on websecure (HTTPS)
      - "traefik.http.routers.whoami.tls.certresolver=myresolver" # Use Let's Encrypt resolver
    networks:
      - web

networks:
  web:
    external: true # Use an external network for all web-facing services

Note: Before running docker-compose up -d, create the external network with docker network create web.
Generate an htpasswd hash for dashboard-auth using echo $(htpasswd -nb user password).

Traefik with Kubernetes

Traefik integrates with Kubernetes through its API, utilizing standard Ingress resources and its own Custom Resource Definitions (CRDs) for advanced configurations. The recommended installation method is via Helm.

Installation with Helm

helm repo add traefik https://traefik.github.io/charts
helm repo update
helm install traefik traefik/traefik \
  --namespace traefik \
  --create-namespace \
  -f values.yaml

The values.yaml file typically configures Traefik's EntryPoints, Providers, and ACME resolvers (e.g., myresolver for Let's Encrypt).

Configuration via Custom Resource Definitions (CRDs)

Traefik extends Kubernetes capabilities with its own CRDs, offering more control than standard Ingress:
* IngressRoute: Defines routing rules, entry points, and associated services, including TLS configuration and middlewares. This is a more powerful alternative to the standard Kubernetes Ingress.
* Middleware: Defines reusable request/response modifiers that can be applied to IngressRoutes.
* TraefikService: Allows defining backend services in more detail, including load balancing strategies and external services.

Example Kubernetes Configuration

This example shows a Kubernetes Deployment, Service, and IngressRoute for a whoami application.

# whoami-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: whoami
  labels:
    app: whoami
spec:
  replicas: 2
  selector:
    matchLabels:
      app: whoami
  template:
    metadata:
      labels:
        app: whoami
    spec:
      containers:
      - name: whoami
        image: traefik/whoami
        ports:
        - containerPort: 80

---
# whoami-service.yaml
apiVersion: v1
kind: Service
metadata:
  name: whoami
spec:
  selector:
    app: whoami
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80

---
# whoami-ingressroute.yaml
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: whoami-ingressroute
spec:
  entryPoints:
    - websecure # Assumes 'websecure' entry point is configured in Traefik's Helm values
  routes:
    - match: Host(`whoami.yourdomain.com`)
      kind: Rule
      services:
        - name: whoami # Refers to the Kubernetes Service 'whoami'
          port: 80
  tls:
    certResolver: myresolver # Assumes 'myresolver' for Let's Encrypt is configured in Traefik's Helm values

Comparison: Traefik vs. Traditional Proxies (Nginx/HAProxy)

Feature Traefik Nginx/HAProxy (Traditional)
Configuration Model Dynamic, API-driven, automatic discovery Static files, manual updates, requires reload/restart
Service Discovery Built-in for Docker, K8s, Consul, etc. Requires external tools (e.g., consul-template) or manual configuration
SSL/TLS Management Automatic Let's Encrypt integration Manual setup, external tools or scripts for automation
Complexity for Dynamic Env. Low, integrates natively, simple labels/CRDs High, complex scripting or orchestration needed for automation
Dashboard Built-in web UI Typically no built-in, third-party monitoring tools
Primary Use Case Microservices, ephemeral containers, cloud-native environments Stable, long-running services, high-performance edge proxy

Monitoring and Dashboard

The Traefik dashboard provides a graphical interface to visualize the current routing configuration and monitor Traefik's status. It can be accessed via a web browser, typically on port 8080 (as configured in the Docker example). For security, it is standard practice to protect the dashboard with a middleware like basic authentication.

Best Practices

  • Isolate Traefik: Run Traefik in a dedicated network or Kubernetes namespace to enhance security and simplify management.
  • Secure Dashboard: Always protect the Traefik dashboard with authentication (e.g., BasicAuth middleware) and ensure it's exposed only to authorized personnel.
  • Persistent Storage for ACME: For Let's Encrypt certificates, ensure the ACME storage path (e.g., /letsencrypt/acme.json) is mapped to persistent storage. This prevents certificate loss upon container restart or redeployment.
  • Least Privilege: When mounting the Docker socket (/var/run/docker.sock), ensure Traefik runs with the minimum necessary privileges. Consider using a read-only mount (:ro) if write access is not required.
  • exposedbydefault=false: For Docker providers, setting --providers.docker.exposedbydefault=false is a security and management best practice. This requires explicit traefik.enable=true labels on containers that should be exposed.
Auto-update: 04.03.2026
All Categories

Advantages of our proxies

25,000+ proxies from 120+ countries