AlgoViz

Traefik

easy 25 min

Traefik (say "traffic") is a reverse proxy that configures itself.

Video lesson · Chapter 1 of 5

A shop appears without editing each proxy

0:00 / 4:00

Traefik in 90 seconds

1:30Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Traefik Proxy is a reverse proxy and load balancer written in Go, under the MIT licence. It stands at the edge, ends TLS, and passes each request to one of your services.

What makes it different is where its routes come from. It connects to providers such as Docker, Kubernetes, Consul or a file, reads what is running there, and updates its routes whenever that changes.

It separates two kinds of settings. The install configuration (which ports, which providers) is read at start. The routing configuration (which request goes where) arrives from the providers and changes without a restart or a lost connection.

Why it exists

In a container platform, addresses are short-lived. A copy starts, moves and stops many times a day. A proxy whose list of servers sits in a hand-written file is wrong most of the time, or somebody builds a script that rewrites the file and reloads it.

The platform already knows which containers run and where. So the proxy can ask it. A team then describes a route next to its own service, as a label or a resource, and nobody else has to act.

A short history

  1. September 2015

    The repository appears on GitHub.

  2. July 2016

    Version 1.0.0.

  3. September 2019

    Version 2.0.0 brings routers, middlewares and services, and TCP.

  4. April 2024

    Version 3.0.0.

  5. November 2025

    From 3.6 on, each minor version is supported for six months.

  6. November 2026

    Version 3.8.0. The 3.7 line from May 2026 also still gets releases.

Words to know

Provider
A source of routes: Docker, Kubernetes, Consul, a file and others.
Entry point
A named port, such as websecure on 443.
Router
A rule plus the middlewares and the service it leads to.
Middleware
A step between router and service: a limit, a login, a rewrite.
Service
A group of servers and how to balance over them.
Label
A key and value on a container. Traefik reads those that start with traefik.
ACME
The protocol by which certificates are issued automatically, for example by Let's Encrypt.
Certificate resolver
Traefik's setting for one way to get certificates.

How it works

Step through the idea, or press Play.

Step 1 of 3

Watch. A provider reports what runs

Understand it

Start here

The signpost that repaints itself

Imagine a village with one signpost at the gate. Shops open and close every week. Who keeps the signpost right?

A sign goes up, the post knows
SHOESSHOESbread?The painter is always late

The shops look after their own signs. The post only copies them.

The idea

Ask the platform

One machine with Docker

Browsers send HTTPS to Traefik on one machine with Docker. Traefik reads labels and events from a read-only Docker API and passes HTTP to the containers shop and blog.
Orange is discovery. Requests never pass through the Docker API.
  • Discovery

    Docker, Swarm, Kubernetes, Nomad, ECS, Consul, etcd, Redis, files, HTTP and more.

  • Routing

    By host, path, method, header, query and client address, combined with and, or, not.

  • Certificates

    ACME with three kinds of proof, and automatic renewal.

  • Middlewares

    Limits, retries, circuit breaker, login, headers, compression, redirects.

  • Protocols

    HTTP/1.1, HTTP/2, HTTP/3, gRPC, WebSocket, plain TCP and UDP.

  • Sight

    Dashboard, access logs, metrics and traces.

The general ideas have their own pages: service discovery, load balancing, Kubernetes load balancing and API gateway.

Model

Entry point, router, middleware, service

The path of a request

Two kinds of configuration

Install configurationRouting configuration
Once calledStaticDynamic
ContainsEntry points, providers, certificate resolvers, logsRouters, middlewares, services, TLS options
Comes fromOne of: a file, arguments, environment variablesThe providers
Change it byRestartNothing: it is watched
The three sources of the install configuration exclude each other. Do not mix a file and arguments.
YAML
services:  traefik:    image: traefik:v3.8    command:      - --entrypoints.web.address=:80      - --entrypoints.web.http.redirections.entrypoint.to=websecure      - --entrypoints.web.http.redirections.entrypoint.scheme=https      - --entrypoints.websecure.address=:443      - --providers.docker=true      - --providers.docker.endpoint=tcp://socket-proxy:2375      - --providers.docker.exposedbydefault=false      - --certificatesresolvers.le.acme.email=ops@shop.example      - --certificatesresolvers.le.acme.storage=/data/acme.json      - --certificatesresolvers.le.acme.httpchallenge.entrypoint=web    ports: ["80:80", "443:443"]    volumes: ["le-data:/data"]    networks: [edge, docker-api]  shop:    image: registry.example/shop:1    labels:      - traefik.enable=true      - traefik.http.routers.shop.rule=Host(`shop.example`)      - traefik.http.routers.shop.entrypoints=websecure      - traefik.http.routers.shop.tls.certresolver=le      - traefik.http.services.shop.loadbalancer.server.port=8080      - traefik.http.services.shop.loadbalancer.healthcheck.path=/health    networks: [edge]# socket-proxy: a small program that only lets Traefik read containers.# Add it as a service, and declare the networks edge and docker-api and the volume le-data.
The shape of a Compose file. The shop says everything about its own route.

Discovery

From event to route

A container starts

Some providers

ProviderReadsWhere a team writes its route
docker, swarmContainers or services and their labelsCompose file
kubernetescrdIngressRoute and other custom resourcesManifest of the service
kubernetesgatewayGateway API (standard channel)HTTPRoute
kubernetesIngressNGINXIngresses with ingress-nginx annotationsNothing changes: a way to migrate
consulcatalog, nomad, ecsServices and their tags or labelsService definition
fileYAML or TOML, watchedA shared file
Objects can refer to each other across providers with an @, for example auth@file.

How late can a route be?

tnew route≤tevent+tthrottle0.1 s+2 s=2.1 st_{\text{new route}} \le t_{\text{event}} + t_{\text{throttle}} \qquad 0.1\,\text{s} + 2\,\text{s} = 2.1\,\text{s}
After a reload Traefik waits at least 2 seconds (the default of providersThrottleDuration) before the next one, and keeps only the newest state. The 0.1 s is assumed.

Rules

Which router wins

Rules are combined with &&, || and !. Routers are tried from the highest priority down and the first match wins. Without a number, the priority is the length of the rule in characters. Long rules are usually more specific, so this often works, but not always.

Length decides, until you decide

RuleCharactersTried
The exact host a.test14Third
A short HostRegexp for any name in .test28Second
The host and a path prefix /api36First
A request for a.test/ meets the regular expression before the exact host. Give the exact one priority=100.

What the status code tells you

404 from Traefik means no route, not a missing page. Check labels, host name and entry point first.

Middlewares

Steps on the way

MiddlewareDoesKnow this
rateLimitToken bucket per sourceaverage 0 means off, burst 1 by default; per instance unless you use Redis
retryTries again on failurePOST and PATCH only if you allow it
circuitBreakerOpens on an expressionChecked every 100 ms, 10 s open, 10 s recovery; state per router
forwardAuthAsks another service about each requestOne more call per request
inFlightReqLimits requests at the same timeProtects slow services
headers, stripPrefix, compressChange the request or answerOrder in the list counts
ipAllowListLets only some addresses inMind the proxies in front
YAML
# labels of a container: a limit, then a circuit breakerlabels:  - traefik.http.middlewares.slow.ratelimit.average=20  - traefik.http.middlewares.slow.ratelimit.burst=40  - traefik.http.middlewares.cut.circuitbreaker.expression=ResponseCodeRatio(500, 600, 0, 600) > 0.25  - traefik.http.routers.shop.middlewares=slow,cut
20 a second on average, up to 40 at once. The circuit only sees what comes after it in the list.

Token bucket on two instances

in 10 s≤2×(40+20×10)=480promised: 40+200=240\text{in 10 s} \le 2 \times (40 + 20 \times 10) = 480 \qquad \text{promised: } 40 + 200 = 240
Each instance has its own bucket. Use the Redis option for one shared bucket, or say that the limit is per instance.

More than the built-in steps: plugins in Go run inside an interpreter (Yaegi), others as WebAssembly. The documentation lists them under experimental features and asks for care in production.

TLS

Certificates without hands

Three ways to prove that the name is yours

ChallengeThe authority checksUse it when
HTTP-01A token on port 80One public instance, port 80 open
TLS-ALPN-01A special TLS handshake on port 443Port 80 is closed
DNS-01A DNS recordWildcard names, or nothing is reachable from outside

Certificates are stored in one file. Traefik assumes 90 days and renews 30 days before the end (certificatesDuration, 2160 hours). Let's Encrypt has announced shorter lifetimes: 64 days by default from February 2027 and 45 by 2028, so keep Traefik current and watch expiry in your metrics.

Who should own the certificates?

Balancing

Servers, health and draining

StrategyRuleUse it when
wrr (default)In turn, by weightServers are alike
p2cTwo random servers, the one with fewer connectionsRequests differ in length
leasttimeLowest response time and fewest connectionsServers differ in speed
hrwHash of the client address (consistent hashing)Same client, same server
Sticky cookieA cookie names the serverSticky sessions you cannot avoid
  1. 1

    Active checks

    Off until you set a path; then every 30 seconds with a timeout of 5 seconds by default. 2xx and 3xx are healthy.

  2. 2

    Passive checks

    One failed try within 10 seconds takes a server out for 10 seconds, by default, once switched on.

  3. 3

    Service of services

    Weights for a canary, mirroring of a share, and failover to a second service.

  4. 4

    Stopping Traefik

    Active requests get 10 seconds (graceTimeOut). Set requestAcceptGraceTimeout so that the balancer in front notices first.

Clusters

Traefik in Kubernetes

Two instances, shared knowledge

Users reach a cloud load balancer that spreads traffic over two Traefik instances on two nodes of a Kubernetes cluster. Both watch the Kubernetes API for routes and secrets, and both send requests to the shop pods.
Routes and certificates come from the Kubernetes API, so both instances know the same.
YAML
apiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata: { name: shop, namespace: shop }spec:  parentRefs: [{ name: public, namespace: edge }]  hostnames: ["shop.example"]  rules:    - matches: [{ path: { type: PathPrefix, value: / } }]      backendRefs:        - { name: shop-v1, port: 80, weight: 95 }        - { name: shop-v2, port: 80, weight: 5 }
Gateway API: the same file works with other implementations, such as Envoy Gateway or Istio.

Traefik is also the ingress controller that K3s, a small Kubernetes distribution, deploys by default. After the retirement of ingress-nginx (see NGINX), its provider for ingress-nginx annotations is one path away from it. It supports many annotations, not all: test each one you use.

Safety

Four doors to close

  • The platform's API

    Full access to the Docker API means control of the machine. Put a filtering proxy in between; in Kubernetes give only the rights in the documentation.

  • The dashboard

    Not recommended in production without a login. api.insecure serves it without one: never outside a test.

  • Forwarded headers

    Trust X-Forwarded-* only from the addresses in trustedIPs.

  • Labels are power

    Who can set labels can claim any host name. Use constraints, namespaces and reviews.

Operations

Running it

QuestionAnswer
How big?Measure with your TLS and middlewares. It is one Go process that uses all cores given to it
Timeouts?Reading a request 60 s, idle connections 180 s, writing an answer unlimited by default
High availability?Two or more instances behind a balancer or a virtual IP; certificates from outside; limits in Redis
If the platform's API is down?Known routes stay in memory and go on. A restarted instance learns nothing until it is back
What to watch?Requests and errors per router and service, configuration reload time and failures, certificate expiry
How to upgrade?Minor versions are supported for six months. Read the migration notes: v1 configuration does not work on v2, and v3 changed rule syntax

Decide

Traefik or something else

ProductStrong atChoose it instead when
NGINXFiles, response cache, fine tuningServers rarely change, or you need a cache
HAProxyBalancing with deep controlLoad balancing itself is the hard part
EnvoyDynamic by API, base of meshesA platform team builds on it
KongConsumers, keys, pluginsYou publish APIs to partners
Cloud balancerNothing to runOne cloud, few routes

Strengths

  • Routes live next to the service
  • No reload, no script
  • Certificates included
  • Small to start, one program

Costs

  • No response cache in the open source proxy
  • Built-in ACME is for one instance
  • Needs access to the platform's API
  • Labels in many places are hard to review

Summary

The whole topic in one minute.

Traefik asks the platform what is running and turns the answer into routers, middlewares and services. Labels on containers or resources in Kubernetes are the configuration, and changes take effect within seconds without a restart.

That convenience needs three decisions: which containers may be public (exposedByDefault false), how Traefik reaches the platform's API safely, and who owns certificates once there are two instances. Set priorities by hand when rules overlap, and add health checks, limits and a graceful shutdown as with any proxy.

  • Providers report, Traefik builds routes, nobody reloads.
  • Entry point, router, middlewares in order, service, server.
  • The longest rule wins unless you set a priority.
  • exposedByDefault false, no raw Docker socket, a login on the dashboard.
  • With two instances, certificates and exact limits come from outside.

Sources