Mastering Traefik: A Complete Guide to Cloud‑Native Reverse Proxy and Load Balancing
This guide explains Traefik’s core concepts—EntryPoints, Routers, Middlewares, and Services—showing how to configure static and dynamic settings, apply routing rules, use built‑in middlewares, implement weighted load balancing, health checks, and failover, and deploy Traefik with Docker or Kubernetes.
Traefik is an open‑source reverse proxy and load balancer that automatically balances traffic among multiple micro‑service instances and supports HTTP, HTTPS, TCP, UDP, and other protocols.
It is simple to use, supports automatic service discovery, dynamic configuration, and pluggable middlewares, making it popular in cloud‑native and containerized environments.
Traefik supports many back‑ends such as Kubernetes, Docker Swarm, Mesos, Consul, Etcd, Zookeeper, Redis, and provides APIs and a dashboard for configuration and monitoring.
Basic Concepts
Traefik has four core concepts: EntryPoints, Routers, Middlewares, and Services.
EntryPoints
EntryPoints define network entry points, configure ports and protocols (HTTP, HTTPS, TCP, UDP). Each has a unique identifier and can have different access rules and routing strategies.
Static configuration example:
## Static configuration
entryPoints:
web:
address: ":80"
websecure:
address: ":443"
streaming:
address: ":1704/udp"Routers
Routers connect incoming requests to services and can apply middlewares to modify request data.
Configuration example for routing requests that start with
/footo a backend service:
## Dynamic configuration
http:
routers:
my-router:
rule: "Path(`/foo`)"
service: service-fooRouters can match on host, path, headers, methods, etc. Common rule types include:
Headers(key, value) – request header validation
HeadersRegexp(key, regexp) – header validation with regex
Host(example.com, …) – host validation
HostRegexp(example.com, {subdomain:[a-z]+}.example.com, …) – host regex
Method(GET, …) – HTTP method validation (GET, POST, PUT, DELETE, PATCH, HEAD)
Path(/path, /articles/{cat:[a-z]+}/{id:[0-9]+}) – exact path matching with optional regex
PathPrefix(/products/, …) – prefix matching with regex
Query(foo=bar, bar=baz) – query parameter matching
ClientIP(10.0.0.0/16, ::1) – client IP matching
Middlewares
Middlewares process and transform requests, similar to filters or interceptors. Traefik includes built‑in middlewares such as logging, redirection, authentication, rate limiting, and also supports custom plugins.
Configuration example using Docker labels:
# As a Docker Label
whoami:
image: traefik/whoami
labels:
- "traefik.http.middlewares.foo-add-prefix.addprefix.prefix=/foo"
- "traefik.http.routers.router1.middlewares=foo-add-prefix@docker"Common built‑in middlewares include AddPrefix, BasicAuth, Buffering, Chain, CircuitBreaker, Compress, Headers, IPWhiteList, RateLimit, Retry, etc.
Services
Services represent Traefik‑managed back‑ends. Each service has a unique identifier and can be configured with load‑balancing rules and health‑check policies. Note that these are Traefik services, not the user’s application services.
Dynamic service configuration example:
## Dynamic configuration
http:
services:
my-service:
loadBalancer:
servers:
- url: "http://<private-ip-server-1>:<private-port-server-1>/"
- url: "http://<private-ip-server-2>:<private-port-server-2>/"Request processing flow in Traefik:
The client request is received and parsed by the protocol handler.
The request is matched to a router rule and forwarded through the middleware chain.
The middleware chain executes in order, possibly modifying the request.
The request is sent to the selected backend server.
The backend processes the request and returns a response to Traefik.
Traefik returns the response to the client.
Load Balancing
Traefik implements load balancing with strategies such as round‑robin, random, weighted round‑robin, and weighted random.
When a request arrives, Traefik selects a backend according to the configured strategy. Officially supported strategies are round‑robin and weighted round‑robin.
Weighted Round‑Robin
Example: version v1 weight 3, version v2 weight 1 for canary traffic.
## Dynamic configuration
http:
services:
app:
weighted:
services:
- name: appv1
weight: 3
- name: appv2
weight: 1
appv1:
loadBalancer:
servers:
- url: "http://private-ip-server-1/"
appv2:
loadBalancer:
servers:
- url: "http://private-ip-server-2/"Traffic Mirroring
Mirroring (traffic copy) can duplicate requests to another service, useful for testing.
## Dynamic configuration
http:
services:
mirrored-api:
mirroring:
service: appv1
maxBodySize: 1024
mirrors:
- name: appv2
percent: 10
appv1:
loadBalancer:
servers:
- url: "http://private-ip-server-1/"
appv2:
loadBalancer:
servers:
- url: "http://private-ip-server-2/"Health Check & Failover
Traefik performs health checks (path, interval, timeout) to determine backend availability. In Kubernetes, native health checks may supersede Traefik’s.
## Dynamic configuration
http:
services:
app:
failover:
service: main
fallback: backup
main:
loadBalancer:
healthCheck:
path: /status
interval: 10s
timeout: 3s
servers:
- url: "http://private-ip-server-1/"
backup:
loadBalancer:
servers:
- url: "http://private-ip-server-2/"Deployment
Traefik can be deployed with Docker or Kubernetes.
Docker
Run the Traefik container:
docker run -d -p 8080:8080 -p 80:80 -v $PWD/traefik.yml:/etc/traefik/traefik.yml traefik:v2.10Create a docker‑compose file that defines a whoami service and the reverse‑proxy:
version: '3'
services:
whoami:
# A container that exposes an API to show its IP address
image: traefik/whoami
labels:
- "traefik.http.routers.whoami.rule=Host(`whoami.docker.localhost`)"
reverse-proxy:
# The official v2 Traefik docker image
image: traefik:v2.10
command: --api.insecure=true --providers.docker
ports:
- "80:80"
- "8080:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sockStart the stack:
docker-compose up -d reverse-proxy
docker-compose up -d whoamiTraefik automatically discovers the whoami service and creates a routing rule. Access
http://localhostto see the response. Scaling the whoami service:
docker-compose up -d --scale whoami=2The IP in the response alternates between the two instances, demonstrating load balancing.
Kubernetes
Use Docker Desktop’s built‑in Kubernetes on macOS. Enable it in settings and wait for the cluster to become ready.
Install the Kubernetes Dashboard:
kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.7.0/aio/deploy/recommended.yamlStart the proxy and access the dashboard at
http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/. Create an admin ServiceAccount and ClusterRoleBinding (k8s‑admin.yaml) and retrieve a token to log in.
Deploy Traefik in the cluster. First create a ClusterRole (traefik‑role) that grants read access to services, endpoints, secrets, ingresses, and ingressclasses.
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: traefik-role
rules:
- apiGroups: [""]
resources: ["services","endpoints","secrets"]
verbs: ["get","list","watch"]
- apiGroups: ["extensions","networking.k8s.io"]
resources: ["ingresses","ingressclasses"]
verbs: ["get","list","watch"]
- apiGroups: ["extensions","networking.k8s.io"]
resources: ["ingresses/status"]
verbs: ["update"]Create a ServiceAccount (traefik‑account) and bind it to the role:
kind: ServiceAccount
apiVersion: v1
metadata:
name: traefik-account kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: traefik-role-binding
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: traefik-role
subjects:
- kind: ServiceAccount
name: traefik-account
namespace: defaultDeploy Traefik as a Deployment with the required arguments:
kind: Deployment
apiVersion: apps/v1
metadata:
name: traefik-deployment
labels:
app: traefik
spec:
replicas: 1
selector:
matchLabels:
app: traefik
template:
metadata:
labels:
app: traefik
spec:
serviceAccountName: traefik-account
containers:
- name: traefik
image: traefik:v2.10
args:
- --api.insecure
- --providers.kubernetesingress
ports:
- name: web
containerPort: 80
- name: dashboard
containerPort: 8080Create Services for the web entry point and the dashboard:
apiVersion: v1
kind: Service
metadata:
name: traefik-dashboard-service
spec:
type: LoadBalancer
ports:
- port: 8080
targetPort: dashboard
selector:
app: traefik
---
apiVersion: v1
kind: Service
metadata:
name: traefik-web-service
spec:
type: LoadBalancer
ports:
- port: 80
targetPort: web
selector:
app: traefikApply all resources with a single file (k8s‑traefik.yaml) and verify the dashboard at
http://localhost:8080/dashboard/#/.
Deploy a sample backend (whoami) in the cluster using k8s‑whoami.yaml and expose it via an Ingress. Access
http://localhostto see the service response.
These steps demonstrate how to set up Traefik as a cloud‑native reverse proxy with dynamic routing, middlewares, load balancing, health checks, and failover in both Docker and Kubernetes environments.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.