# Traefik Reverse Proxy Stack

> Complete Traefik setup with automatic SSL, metrics, and service discovery.

- Category: DevOps & CI/CD
- Difficulty: intermediate
- Components: traefik, whoami, prometheus, grafana
- Tags: traefik, reverse-proxy, ssl, lets-encrypt, load-balancer
- Source: https://docker.recipes/devops/traefik-full-stack

## Overview

Traefik is a cloud-native edge router that revolutionizes reverse proxy management through automatic service discovery and dynamic configuration. Originally developed by Containous (now Traefik Labs) in 2015, Traefik eliminates the traditional pain points of manually configuring reverse proxies by automatically detecting Docker containers and Kubernetes services, then routing traffic accordingly. Unlike traditional reverse proxies that require manual configuration updates and service restarts, Traefik continuously monitors your container orchestrator and updates routing rules in real-time.

This comprehensive monitoring stack combines Traefik's intelligent routing capabilities with Prometheus metrics collection and Grafana visualization dashboards. Traefik automatically generates Let's Encrypt SSL certificates for all discovered services while exposing detailed metrics about request patterns, response times, and backend health. Prometheus scrapes these metrics along with system-level data, creating a complete observability pipeline that Grafana transforms into actionable dashboards. The whoami service acts as a perfect test target, demonstrating how Traefik automatically discovers services through Docker labels and provisions SSL certificates without manual intervention.

This stack is ideal for DevOps teams managing microservices architectures, startups building scalable web applications, and infrastructure engineers who need comprehensive traffic monitoring. The combination provides enterprise-grade load balancing, automatic HTTPS, and production-ready observability in a single deployment. Unlike static reverse proxy solutions that require manual certificate management and configuration updates, this dynamic stack adapts automatically as services scale up or down, making it perfect for modern containerized applications that demand flexibility and reliability.

## Features

- Automatic service discovery from Docker containers using label-based configuration
- Zero-downtime Let's Encrypt SSL certificate provisioning and renewal for all services
- Real-time Traefik dashboard showing active routes, middleware, and backend health status
- Prometheus metrics collection with custom buckets for HTTP request duration analysis
- PromQL-powered alerting and time-series analysis of traffic patterns and errors
- Grafana visualization with pre-configured dashboards for Traefik proxy metrics
- Dynamic routing updates without service restarts when containers start or stop
- Middleware support for authentication, rate limiting, and request transformation

## Use cases

- Microservices architecture requiring automatic SSL and service discovery
- Development environments with frequently changing container deployments
- Multi-tenant SaaS platforms needing subdomain routing and SSL automation
- API gateway deployment with comprehensive request monitoring and analytics
- Production workloads requiring zero-downtime certificate renewals and updates
- Container orchestration setups needing detailed traffic metrics and performance monitoring
- Home lab environments running multiple web services with professional SSL certificates

## Prerequisites

- Docker Engine 20.10+ and Docker Compose v2 for container orchestration
- Minimum 1GB RAM for the complete stack (Traefik 128MB, Prometheus 256MB, Grafana 256MB)
- Valid domain name with DNS records pointing to your server for Let's Encrypt certificates
- Ports 80, 443, 8080, and 9090 available and accessible from the internet
- Basic understanding of Docker labels and Traefik routing concepts
- Valid email address for ACME Let's Encrypt certificate notifications

## docker-compose.yml

```yaml
services:
  traefik:
    image: traefik:latest
    ports:
      - "80:80"
      - "443:443"
      - "8080:8080"
    command:
      - "--api.insecure=true"
      - "--api.dashboard=true"
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=false"
      - "--entrypoints.web.address=:80"
      - "--entrypoints.websecure.address=:443"
      - "--entrypoints.web.http.redirections.entryPoint.to=websecure"
      - "--certificatesresolvers.letsencrypt.acme.httpchallenge=true"
      - "--certificatesresolvers.letsencrypt.acme.httpchallenge.entrypoint=web"
      - "--certificatesresolvers.letsencrypt.acme.email=${ACME_EMAIL}"
      - "--certificatesresolvers.letsencrypt.acme.storage=/letsencrypt/acme.json"
      - "--metrics.prometheus=true"
      - "--metrics.prometheus.buckets=0.1,0.3,1.2,5.0"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - traefik_certs:/letsencrypt
    networks:
      - traefik-net
    restart: unless-stopped
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.dashboard.rule=Host(`traefik.${DOMAIN}`)"
      - "traefik.http.routers.dashboard.service=api@internal"

  whoami:
    image: traefik/whoami:latest
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.whoami.rule=Host(`whoami.${DOMAIN}`)"
      - "traefik.http.routers.whoami.entrypoints=websecure"
      - "traefik.http.routers.whoami.tls.certresolver=letsencrypt"
    networks:
      - traefik-net
    restart: unless-stopped

  prometheus:
    image: prom/prometheus:latest
    ports:
      - "9090:9090"
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
      - prometheus_data:/prometheus
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--storage.tsdb.path=/prometheus'
    networks:
      - traefik-net
    restart: unless-stopped

  grafana:
    image: grafana/grafana:latest
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD}
    volumes:
      - grafana_data:/var/lib/grafana
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.grafana.rule=Host(`grafana.${DOMAIN}`)"
      - "traefik.http.routers.grafana.entrypoints=websecure"
      - "traefik.http.routers.grafana.tls.certresolver=letsencrypt"
    depends_on:
      - prometheus
    networks:
      - traefik-net
    restart: unless-stopped

volumes:
  traefik_certs:
  prometheus_data:
  grafana_data:

networks:
  traefik-net:
    driver: bridge
```

## .env

```bash
# Domain Configuration
DOMAIN=example.com
ACME_EMAIL=admin@example.com

# Grafana
GRAFANA_PASSWORD=secure_grafana_password
```

## Usage notes

- Traefik dashboard at http://localhost:8080
- Auto SSL via Let's Encrypt
- Add labels to services for automatic discovery
- Create prometheus.yml with Traefik scrape target

## Troubleshooting

- Let's Encrypt certificate generation fails: Ensure ports 80/443 are accessible from internet and DNS records point to your server
- Traefik dashboard shows 'No route found' errors: Verify Docker labels are correct and containers are on the same Docker network
- Prometheus cannot scrape Traefik metrics: Check that prometheus.yml includes Traefik endpoint at traefik:8080/metrics
- Grafana dashboards show no data: Confirm Prometheus data source is configured correctly with URL http://prometheus:9090
- Services not automatically discovered: Ensure traefik.enable=true label is set and Docker socket is mounted correctly
- SSL redirect loops occurring: Verify entrypoint configuration and check if services are properly configured for HTTPS

