Open menu

How to make Traefik work on docker


Proxy the proxy

Have you just got your docker host setup? Have you just got a container working with an IP and port?

Now you want to access your container from a domain name, like service.home.local. You need a proxy server to take your domain name and connect you to your container, you could use nginx or apache or caddy. They are all good Proxy servers, but as your running docker why not use a docker way?

Traefik is by far the quickest to get setup and working, I should know I manage maybe 10 nginx servers at work. Plus my home nginx pi. What makes it so easy I hear you ask, well its that you simply add some labels to your container and traefik can pickup it has started and setup routing for it. See simple!

Make it so

Now lets get this working, your going to need to start Traefik. The below is a compose file that will start traefik, make listen on ports 80, 443 and 8081. If you copy it and run it with docker-compose up -d , you should have a proxyv2 container listed when running docker ps.

---
version: '3.5'
services:
  proxyv2:
    image: traefik:v2.0 # The official Traefik docker image
    command:
      - "--api.insecure=true"
      - "--providers.docker"
    restart: unless-stopped
    ports:
      - "80:80"     # The HTTP port
      - "443:443"   # The HTTP port
      - "8081:8080" # The Web UI (enabled by --api)
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock # So that Traefik can listen to the Docker events

Now lets get a service working with it, Im going to use my favorate dashboard. Add the below under our proxy server to have a new service start when you rerun docker-compose up -d, now when you run docker ps you should see both proxyv2 and dashmachine

  dashmachine:
    image: supermamon/rpi-dashmachine:latest
    networks:
      - proxy_dashmachine
    volumes:
      - dashmachine:/dashmachine/dashmachine/user_data
    restart: unless-stopped
    labels:
      - "traefik.http.routers.dashmachine.rule=Host(`dashmachine.home.local`)"
      - "traefik.http.routers.dashmachine.service=dashmachine"
      - "traefik.http.services.dashmachine.loadbalancer.server.port=5000"

volumes:
  dashmachine:

The magic happens with the labels, the first label tells traefik that the domain dashmachine.home.local is to get directed to that container. The next label is to map a service to the route, a service is the web server that the container runs and how traefik should connect to it. The last label is the port the container web server is on, if your container is on port 80 then you might not need this.

Now if you setup DNS to point dashmachine.home.local at your docker host, you should now get your container. What, you havent setup DNS yet? checkout my Nextcloud from home post as that will help you get storted.