Intalling Traefik with SSL, Dynamic Files and more on Docker Standalone

Luiz Dores

About Traefik

Traefik is a very versatile reverse proxy and can be used in Docker, Kubernetes or using its own binary.

In this tutorial we will cover the installation of Traefik in Docker Standalone and we will also cover some features such as

  • Generate SSL certificates using DNS01
  • Add routers, services and middlewares dynamically through a traefik folder
  • Create custom labels in traefik
  • Static configuration of Traefik
  • Dynamic configuration of Traefik

Instalation

Clone the repo

git clone https://github.com/luizdores/traefik-swarm.git -b standalone

Create the Traefik network

docker network create --attachable traefik-public

Change the Cloudfare API Token in the docker-compose.yml

environment:
      # Cloudflare API token
      - CF_DNS_API_TOKEN=APIKEY

Generate the Basic Auth User for Traefik

echo $(htpasswd -nb MYUSER MYPASSWD) | sed -e s/\\$/\\$\\$/g

Copy the result to docker-compose.yml

labels:
      ...
      # Middleware Basic Auth
      - "traefik.http.middlewares.admin-auth.basicauth.users=MYUSER:$$apr1$$yjuBx8Nd$$4fRCCxbgB2MQwqaYgPx7L."

Change the Let’s Encrypt notification email in config/config.yaml

certificatesResolvers:
  le:
    acme:
      email: mail@domain.com 
      storage: /certificates/acme.json
      # Production
      caServer: "https://acme-v02.api.letsencrypt.org/directory"
      # Staging
      #caServer: "https://acme-staging-v02.api.letsencrypt.org/directory"

Start traefik

docker compose up -d

Create Dynamic Config Files

Dynamic Config Files allow you to dynamically add entries to Traefik without having to restart it or launch containers, so it is possible to expose other services that are not running on the host where Traefik is located.

The files must be placed in the config/dynamic folder with the .yaml extension.

Here is an example of a simple website with http and https

http:
  routers:
    mysite-http:
      entryPoints:
        - http
      rule: Host(`mysite.com`) || Host(`www.mysite.com`)
      middlewares:
        - https-redirect@docker
      service: portal
    mysite-https:
      entryPoints:
        - https
      rule: Host(`mysite.com`) || Host(`www.mysite.com`)
      tls:
        certResolver: le
      service: mysite

  services:
    portal:
      loadBalancer:
        servers:
          - url: 'http://192.168.1.10'
        passHostHeader: true

Other examples can be found in the examples folder of the repository.

Observations

If you have more than one NIC on your server, you can select which one will be used by Traefik in the docker-compose.yml file.

ports:
  - target: 80 
    published: 80
    mode: host
    host_ip: NIC IP

Acknowledgements