How to Set Up Traefik Reverse Proxy on Ubuntu: Automated Let’s Encrypt SSL for Docker

Ubuntu tutorial - IT technology blog
Ubuntu tutorial - IT technology blog

Quick Start (Up and Running in 5 Minutes)

It’s 2 AM, and PagerDuty won’t stop ringing. All 15 web services on the staging cluster are down with SSL errors because a Certbot cronjob failed to reload Nginx. Instead of painstakingly tweaking individual vhost blocks until dawn, switching to Traefik is the fastest way to get your system auto-provisioning SSL certificates again.

Create a project directory and a certificate storage file with strict permissions:

mkdir -p /opt/traefik && cd /opt/traefik
touch acme.json && chmod 600 acme.json
docker network create web-gateway

Create a docker-compose.yml file for Traefik:

version: '3.8'

services:
  traefik:
    image: traefik:v2.11
    container_name: traefik
    restart: always
    command:
      - "--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"
      - "--entrypoints.web.http.redirections.entrypoint.scheme=https"
      - "--certificatesresolvers.myresolver.acme.tlschallenge=true"
      - "[email protected]"
      - "--certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json"
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock:ro"
      - "./acme.json:/letsencrypt/acme.json"
    networks:
      - web-gateway

networks:
  web-gateway:
    external: true

Start Traefik:

docker compose up -d
docker compose logs -f traefik

Now, spin up a demo service (such as whoami). Traefik will automatically detect the domain and request an SSL certificate without requiring a single reload:

version: '3.8'

services:
  whoami:
    image: traefik/whoami
    container_name: demo-whoami
    restart: always
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.whoami.rule=Host(`demo.yourdomain.com`)"
      - "traefik.http.routers.whoami.entrypoints=websecure"
      - "traefik.http.routers.whoami.tls.certresolver=myresolver"
      - "traefik.http.services.whoami.loadbalancer.server.port=80"
    networks:
      - web-gateway

networks:
  web-gateway:
    external: true

Point the DNS A record for demo.yourdomain.com to your Ubuntu server’s IP address. Then run docker compose up -d. Within just 10 to 15 seconds, HTTPS is fully up and running with a valid Let’s Encrypt certificate.

Under the Hood: How Traefik Works

When managing dozens of containers, Nginx starts showing its limitations: every time you add a new service, you have to edit a .conf file and reload the service. Traefik solves this problem using built-in Service Discovery directly via the Docker daemon.

1. Docker Socket (`/var/run/docker.sock:ro`)

Traefik listens to events from the Docker engine in real time. Whenever you start or stop a container, Traefik inspects its metadata under labels. Its in-memory routing table updates instantly—no process reloads required. The risk of downtime caused by configuration syntax errors drops to zero.

2. EntryPoints, Routers, Services, and Middlewares

Traefik’s routing architecture is divided into four distinct components:

  • EntryPoints: The network ports that receive incoming traffic, typically port 80 (HTTP) and port 443 (HTTPS).
  • Routers: The request analyzers. Rules such as Host(`demo.yourdomain.com`) determine which request maps to which service.
  • Services: The actual destination of the traffic, pointing directly to the internal IP and port where the container is listening.
  • Middlewares: Intermediate checkpoints before a request hits the backend, handling HTTP-to-HTTPS redirects, Basic Auth, rate limiting, and security headers.

3. ACME Protocol and the acme.json File

Traefik comes with a built-in ACME client. When a router requests TLS via certresolver=myresolver, Traefik checks the acme.json file. If the certificate does not exist or expires in less than 30 days, Traefik proactively sends a challenge (using TLS-ALPN-01 over port 443 in this setup) to Let’s Encrypt servers. Once validated, the private key and certificate are securely stored automatically.

Production-Ready Configuration

1. Password-Protecting the Traefik Dashboard

Leaving your dashboard exposed to the public Internet is an open invitation for attackers to inspect your system architecture. Secure it with HTTP Basic Auth. Generate a password hash using htpasswd:

sudo apt update && sudo apt install -y apache2-utils
htpasswd -nb admin SuperSecurePassword123!

The command outputs a string formatted like admin:$apr1$xyz.... Note: The $ character in Docker Compose files must be escaped by doubling it to $$. Add the following labels to your traefik service in compose:

    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.dashboard.rule=Host(`traefik.yourdomain.com`)"
      - "traefik.http.routers.dashboard.service=api@internal"
      - "traefik.http.routers.dashboard.entrypoints=websecure"
      - "traefik.http.routers.dashboard.tls.certresolver=myresolver"
      - "traefik.http.routers.dashboard.middlewares=auth"
      - "traefik.http.middlewares.auth.basicauth.users=admin:$$apr1$$xyz..."

2. Adding Security Headers and Enabling Gzip Compression

To achieve an A+ rating on SSL Labs and boost page load speeds, you should enforce HSTS and enable compression. Attach middlewares directly to the traefik service:

    labels:
      - "traefik.http.middlewares.gzip.compress=true"
      - "traefik.http.middlewares.sec-headers.headers.sslredirect=true"
      - "traefik.http.middlewares.sec-headers.headers.stsseconds=31536000"
      - "traefik.http.middlewares.sec-headers.headers.stsincludesubdomains=true"
      - "traefik.http.middlewares.sec-headers.headers.browserxssfilter=true"
      - "traefik.http.middlewares.sec-headers.headers.contenttypenosniff=true"

To apply these to any service, simply add the label traefik.http.routers.<name>.middlewares=sec-headers@docker,gzip@docker.

Troubleshooting Common Issues

1. Permission Errors on acme.json

This is the most common error encountered by Traefik newcomers. The log will explicitly state:

permissions of /letsencrypt/acme.json are too open, have to be 600, will be ignored

If acme.json has permissions set to 644 or 755, Traefik will refuse to use it due to security risks regarding exposed private keys. Simply fix it with:

chmod 600 /opt/traefik/acme.json

2. Hitting Let’s Encrypt Rate Limits

Let’s Encrypt enforces a limit of 5 failed validations per hostname per hour. During testing and configuration, always point to the ACME Staging Server by adding this flag to the command section:

      - "--certificatesresolvers.myresolver.acme.caserver=https://acme-staging-v02.api.letsencrypt.org/directory"

Certificates issued by staging will trigger a Not Secure warning in your browser. This is completely expected. Once logs confirm everything works smoothly, remove this line to obtain a production certificate.

3. Handling 404 Not Found or 504 Gateway Timeout Errors

Set the log level to DEBUG in your compose file to inspect the request workflow in detail:

      - "--log.level=DEBUG"

Then monitor the logs in your terminal:

docker logs -f traefik --tail 50 | grep -iE "error|acme|router"

In practice, 90% of 404 errors stem from either a mismatched Host(...) rule or forgetting to attach the backend service to the shared web-gateway network. Traefik cannot route traffic to containers unless they reside on the same internal network.

Share: