← Recipes

阅读中文版本

Chain Traefik Middlewares for Defense in Depth

Compose rate limiting, security headers, and a circuit breaker as labeled middlewares so every routed service inherits the same protections.

~40 mintraefikreliabilitysecurity

Task

Apply a reusable chain of Traefik middlewares to all services via labels or a CRD.

When to use this

Each service configures its own protections inconsistently, so some routes lack headers or rate limiting and a single slow backend can cascade.

Prerequisites

  • Traefik v2+
  • Services exposing Traefik labels or IngressRoute CRDs

Steps

1. Define the individual middlewares: retry, rate limit, headers, circuit breaker.

Expected output: Each protection is a named, reusable unit.

2. Compose them into a chain in a deliberate order.

Expected output: Order is explicit and shared.

3. Attach the chain to services via labels or a CRD.

Expected output: Services inherit the same protections.

4. Verify headers and status behavior against a canary route.

curl -sI https://app.example.com | grep -iE "x-ratelimit|strict-transport"

Expected output: The chain is proven to be active.

Troubleshooting

Problem

Broken order disables a protection

Solution

Order matters: put security headers early and the circuit breaker around the backend call; document the intended sequence.

Problem

Chain applied to health checks

Solution

Exclude health endpoints from rate limiting so probes are not throttled.

Limitations

  • Middleware chains add latency per request and can obscure where a response was altered.
  • Provider-specific label syntax makes chains harder to reuse across providers without a CRD.

Context

Apply a reusable chain of Traefik middlewares to all services via labels or a CRD. Each service configures its own protections inconsistently, so some routes lack headers or rate limiting and a single slow backend can cascade.

Steps

  1. Define the individual middlewares: retry, rate limit, headers, circuit breaker. Expected: Each protection is a named, reusable unit.
  2. Compose them into a chain in a deliberate order. Expected: Order is explicit and shared.
  3. Attach the chain to services via labels or a CRD. Expected: Services inherit the same protections.
  4. Verify headers and status behavior against a canary route. Expected: The chain is proven to be active.
http:
  middlewares:
    chain1:
      chain:
        middlewares: [secure-headers, rate-limit, cb]
  services:
    app:
      loadBalancer:
        servers: [{ url: "http://127.0.0.1:3000" }]

Verify

  • Each protection is a named, reusable unit.
  • Order is explicit and shared.
  • Services inherit the same protections.
  • The chain is proven to be active.

Limits

  • Middleware chains add latency per request and can obscure where a response was altered.
  • Provider-specific label syntax makes chains harder to reuse across providers without a CRD.