Guewen Baconnier

(ノ◕ヮ◕)ノ*:・゚✧

Docker, Traefik and dnsmasq

If you have ever been in the situation that need more than one local http service running on your local machine and reachable with a DNS rather than different ports, this setup might be interesting for you.

dnsmasq is a light DNS forwarder, which proves to be very useful in the use case described here. Traefik is a fast, modern HTTP reverse proxy and load balancer perfectly designed for Docker (impressive work).

The setup we are trying to have here is the following:

We'll see how to configure them.

Configuration of dnsmasq

Install dnsmasq if needed

sudo apt install dnsmasq

Active dnsmasq for listening requests from localhost, edit /etc/dnsmasq.conf and ensure you have this line

listen-address=127.0.0.1

Configure your domain by creating a file /etc/dnsmasq.d/localhost.conf containing

address=/localhost/127.0.0.1

Which means that all requests to any subdomain of .localhost will be forwarded to 127.0.0.1

Edit /etc/dhcp/dhclient.conf and uncomment the following line, so the DHCP client will use the local dnsmasq forwarder.

prepend domain-name-servers 127.0.0.1;

Restart dnsmasq, active it to start automatically

systemctl restart dnsmasq
systemctl enable dnsmasq

And apply the new DHCP config

dhclient

Using Traefik in a docker-compose configuration

version: '2'
services:

  whoami:
    image: emilevauge/whoami
    labels:
      - "traefik.frontend.rule=Host:whoami.docker.localhost"

  whoami2:
    image: emilevauge/whoami
    labels:
      - "traefik.frontend.rule=Host:whoami2.docker.localhost"

  traefik:
    image: traefik
    command: --api --docker #Enables the web UI and tells Træfik to listen to docker
    ports:
      - "80:80"     #The HTTP port
      - "8080: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

Start it with

docker-compose up

Now heads on http://whoami.docker.localhost/ and http://whoami2.docker.localhost/, hurray!

Oh, and the icing on the cake, open the Traefik dashboard on http://localhost:8080. You should see the whoamis frontends and backends listed.

You could also start only one traefik container globally on your machine, but then you would have to share a network with your docker-compose composition.

Comments