Traefik: Entry Points, Routers & Services
Traefik was built for environments where backends come and go: containers, Kubernetes pods, autoscaled VMs. Instead of a config file listing every backend, it reads its routing table from providers (Docker labels, Kubernetes resources, Consul, ECS, files) and updates it live as they change. In Kubernetes it is a popular Ingress and Gateway API controller (it is k3s's default), and with the Docker provider a container announces its own routes through labels. This course uses the file provider, which shows every concept without Docker or a cluster.
Static and dynamic configuration
| Static configuration | Dynamic configuration | |
|---|---|---|
| Contains | entry points (ports), providers, API/dashboard, logs, metrics | routers, services, middlewares, TLS certificates |
| Source | traefik.yml, CLI flags or environment variables |
providers: files, Docker labels, Kubernetes objects… |
| Changes | need a restart | applied live |
The request path is entry point → router → middlewares → service → server:
- An entry point is a listening address (
:80,:443). - A router matches requests with a rule (
Host(\shop.example`) && PathPrefix(`/api`)`) on some entry points, applies middlewares and sends them to a service. - A service load-balances across servers (or combines other services: weighted, mirroring, failover).
Rules can use Host, HostRegexp, Path, PathPrefix, PathRegexp, Method, Header, HeaderRegexp, Query, ClientIP, combined with &&, ||, ! and parentheses. When several routers match, the one with the higher priority wins; by default the priority is the length of the rule, so more specific rules usually win without any configuration.
A first Traefik
cat > app.py <<'EOF'
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
def do_GET(self):
code = 503 if (self.path == "/health" and sys.argv[2] == "broken") else 200
self.send_response(code); self.end_headers(); self.wfile.write(f"{sys.argv[2]} {self.path}\n".encode())
def log_message(self, *a): pass
HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
EOF
python3 app.py 9001 web & python3 app.py 9002 api-1 & python3 app.py 9003 api-2 & python3 app.py 9004 broken &
cat > traefik.yml <<'EOF'
global:
checkNewVersion: false
sendAnonymousUsage: false
entryPoints:
web:
address: "127.0.0.1:8080"
traefik: # the API/dashboard entry point
address: "127.0.0.1:8081"
api:
insecure: true # serve the API on the "traefik" entry point (lab only!)
providers:
file:
filename: dynamic.yml
watch: false # see the note below
log:
level: ERROR
EOF
cat > dynamic.yml <<'EOF'
http:
routers:
site:
rule: "Host(`shop.test`)"
entryPoints: [web]
service: web
api:
rule: "Host(`shop.test`) && PathPrefix(`/api`)" # longer rule: higher default priority
entryPoints: [web]
service: api
services:
web:
loadBalancer:
servers:
- url: "http://127.0.0.1:9001"
api:
loadBalancer:
healthCheck:
path: /health
interval: 500ms
timeout: 1s
servers:
- url: "http://127.0.0.1:9002"
- url: "http://127.0.0.1:9003"
- url: "http://127.0.0.1:9004"
EOF
traefik --configFile=traefik.yml > traefik.log 2>&1 &
for i in $(seq 100); do curl -s 127.0.0.1:8081/api/http/services/api@file | grep -q '"DOWN"' && break; sleep 0.1; done
get() { curl -s -H "Host: $1" "127.0.0.1:8080$2"; }
get shop.test /products
echo "4 x /api/orders: $(for i in 1 2 3 4; do get shop.test /api/orders; done | sort | uniq -c | xargs)"
echo "unknown host: $(curl -s -w '[%{http_code}]' -H 'Host: other.test' 127.0.0.1:8080/ | tr -d '\n')"
echo "--- routers (from the API):"
curl -s 127.0.0.1:8081/api/http/routers | jq -r '.[] | select(.provider=="file") | "\(.name) priority=\(.priority) rule=\(.rule)"'
echo "--- api service server status:"
curl -s 127.0.0.1:8081/api/http/services/api@file | jq -r '.serverStatus | to_entries[] | "\(.key) \(.value)"' | sort
kill %5 %1 %2 %3 %4web /products
4 x /api/orders: 2 api-1 /api/orders 2 api-2 /api/orders
unknown host: 404 page not found[404]
--- routers (from the API):
api@file priority=39 rule=Host(`shop.test`) && PathPrefix(`/api`)
site@file priority=17 rule=Host(`shop.test`)
--- api service server status:
http://127.0.0.1:9002 UP
http://127.0.0.1:9003 UP
http://127.0.0.1:9004 DOWN
- The two routers overlap (
shop.test/api/...matches both); the API router won because its rule is longer, as the priorities from the API show. Setpriority:explicitly when the length heuristic is wrong (for example a catch-allHostRegexpwith a long regex). - The health check took the broken server out: requests alternated between
api-1andapi-2only. - An unmatched host got Traefik's plain
404 page not found. - Names get a provider suffix (
api@file): routers from one provider can reference services of another (service: api@docker).
watch: false appears in this course's recorded sessions only because the machine that records them can't spare file watchers; each session writes its files once and never edits them. On a server, leave the default watch: true: Traefik then reloads the dynamic file whenever it changes, so editing dynamic.yml is a live, graceful configuration change, and a file with errors is logged and ignored while the last good configuration keeps running.
Weighted services: canary and blue/green
A weighted service splits traffic between other services, which is how canary releases and blue/green switches are done with the file provider (or with labels and CRDs in Docker and Kubernetes):
cat > app.py <<'EOF'
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200); self.end_headers(); self.wfile.write(f"{sys.argv[2]}\n".encode())
def log_message(self, *a): pass
HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
EOF
python3 app.py 9001 v1 & python3 app.py 9002 v2 &
cat > traefik.yml <<'EOF'
global: {checkNewVersion: false, sendAnonymousUsage: false}
entryPoints:
web: {address: "127.0.0.1:8080"}
traefik: {address: "127.0.0.1:8081"}
api: {insecure: true}
providers:
file: {filename: dynamic.yml, watch: false}
log: {level: ERROR}
EOF
cat > dynamic.yml <<'EOF'
http:
routers:
app:
rule: "PathPrefix(`/`)"
service: app
services:
app:
weighted:
services:
- name: v1
weight: 9
- name: v2
weight: 1
v1:
loadBalancer:
servers: [{url: "http://127.0.0.1:9001"}]
v2:
loadBalancer:
servers: [{url: "http://127.0.0.1:9002"}]
EOF
traefik --configFile=traefik.yml > traefik.log 2>&1 &
for i in $(seq 100); do curl -sf 127.0.0.1:8081/api/http/routers/app@file > /dev/null && break; sleep 0.1; done
for i in $(seq 100); do curl -s 127.0.0.1:8080/; done | sort | uniq -c | xargs
kill %3 %1 %290 v1 10 v2
Exactly 90 / 10 over 100 requests: Traefik's weighted round-robin is deterministic, not random. Moving the canary forward is changing the two weights in the file; switching blue/green is setting one weight to 0. Other compound services: mirroring (send a copy of a percentage of requests to a second service, discarding its answers: a way to test a new version with real traffic) and failover (use a fallback service when the main one's health check fails).
Test yourself
Where are routers and services defined in Traefik?
- In the static configuration
- In the dynamic configuration, delivered by providers (files, Docker labels, Kubernetes objects)
- Only in the dashboard
- In entry points
Two routers match a request. Without explicit priorities, which wins?
- The first one in the file
- The one with the longer rule
- The one defined by Docker
- Both, alternating
How do you send 10 % of traffic to a new version with the file provider?
- A middleware
- A
weightedservice with weights 9 and 1 pointing at the two version services - Two entry points
- A health check