Traefik is a modern reverse proxy and load balancer that automatically discovers services. Its built-in API and dashboard let you monitor routes, services, and middlewares in real-time — all for free.
Why Use the Traefik API?
- Monitor all routes and their health status
- Debug routing issues in real-time
- Integrate proxy metrics into your monitoring stack
- Auto-discover services from Docker, Kubernetes, and more
Getting Started
Enable the API in traefik.yml:
api:
dashboard: true
insecure: true # For development only
providers:
docker:
exposedByDefault: false
# List all routers
curl -s http://localhost:8080/api/http/routers | jq '.[] | {name: .name, rule: .rule, service: .service, status: .status}'
# List all services
curl -s http://localhost:8080/api/http/services | jq '.[] | {name: .name, status: .status, loadBalancer: .loadBalancer.servers}'
# List middlewares
curl -s http://localhost:8080/api/http/middlewares | jq '.[] | {name: .name, type: .type, status: .status}'
Python Client
import requests
class TraefikClient:
def __init__(self, url='http://localhost:8080'):
self.url = f"{url}/api"
def get_routers(self, provider=None):
resp = requests.get(f"{self.url}/http/routers")
routers = resp.json()
if provider:
routers = [r for r in routers if r.get('provider') == provider]
return routers
def get_services(self):
resp = requests.get(f"{self.url}/http/services")
return resp.json()
def get_middlewares(self):
resp = requests.get(f"{self.url}/http/middlewares")
return resp.json()
def get_entrypoints(self):
resp = requests.get(f"{self.url}/entrypoints")
return resp.json()
def get_overview(self):
resp = requests.get(f"{self.url}/overview")
return resp.json()
# Usage
traefik = TraefikClient()
# Overview
overview = traefik.get_overview()
print(f"HTTP: {overview['http']['routers']['total']} routers, {overview['http']['services']['total']} services")
print(f"TCP: {overview.get('tcp', {}).get('routers', {}).get('total', 0)} routers")
# List all routes
for router in traefik.get_routers():
print(f"{router['name']:30s} Rule: {router['rule'][:50]:50s} Status: {router['status']}")
Health Monitoring Dashboard
def proxy_health_report(traefik):
routers = traefik.get_routers()
services = traefik.get_services()
# Router status
enabled = sum(1 for r in routers if r['status'] == 'enabled')
disabled = len(routers) - enabled
print(f"Routers: {enabled} enabled, {disabled} disabled")
# Service health
print("\nService Health:")
for svc in services:
name = svc['name']
status = svc.get('status', 'unknown')
servers = svc.get('loadBalancer', {}).get('servers', [])
server_urls = [s.get('url', 'N/A') for s in servers]
print(f" {name:30s} {status:10s} Backends: {', '.join(server_urls[:3])}")
# Check for issues
disabled_routers = [r for r in routers if r['status'] != 'enabled']
if disabled_routers:
print("\nWARNING - Disabled routers:")
for r in disabled_routers:
print(f" {r['name']}: {r.get('error', 'unknown error')}")
proxy_health_report(traefik)
Docker Auto-Discovery
# docker-compose.yml
version: '3'
services:
traefik:
image: traefik:v3.0
ports:
- "80:80"
- "8080:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
command:
- --api.insecure=true
- --providers.docker
- --providers.docker.exposedByDefault=false
my-api:
image: my-api:latest
labels:
- "traefik.enable=true"
- "traefik.http.routers.api.rule=Host(`api.example.com`)"
- "traefik.http.services.api.loadbalancer.server.port=3000"
- "traefik.http.routers.api.middlewares=rate-limit"
- "traefik.http.middlewares.rate-limit.ratelimit.average=100"
- "traefik.http.middlewares.rate-limit.ratelimit.burst=50"
Middleware Configuration via API
def analyze_middleware_chain(traefik):
routers = traefik.get_routers()
middlewares = traefik.get_middlewares()
middleware_map = {m['name']: m for m in middlewares}
for router in routers:
chain = router.get('middlewares', [])
if chain:
print(f"\n{router['name']} ({router['rule'][:40]}):")
for mw_name in chain:
mw = middleware_map.get(mw_name, {})
mw_type = mw.get('type', 'unknown')
print(f" -> {mw_name} ({mw_type})")
analyze_middleware_chain(traefik)
SSL Certificate Status
# Check TLS certificates
curl -s http://localhost:8080/api/tls/certificates | jq '.[] | {domain: .sans[0], notAfter: .notAfter}'
Real-World Use Case
A startup ran 30+ microservices behind Traefik with Docker auto-discovery. When a new service container starts, Traefik automatically configures routing, SSL, and rate limiting — zero manual config. They built a status page using the Traefik API showing real-time routing health. The entire proxy setup for a new service takes exactly one label in docker-compose.
What You Can Build
- Service mesh dashboard showing all routes and health
- Auto-SSL manager monitoring certificate expiry
- Traffic analyzer tracking request patterns
- Canary deployer splitting traffic between versions
- Rate limit manager adjusting limits based on load
Need custom proxy automation? I build infrastructure tools and DevOps pipelines.
Email me: spinov001@gmail.com
Check out my developer tools: https://apify.com/spinov001
Top comments (0)