Traefik

In my previous post, I talked about using Fabio to handle routing for our container services.

Here, I will talk about yet another router called Traefik. What’s great about it is that it don’t even require Consul to discover our deployments.

The following guide is for a one cluster/one node setup. I will try to write a separate article on how we can use Traefik on a multi node setup.

Requirements: Docker

Le’t get started.

First, let’s create a docker-compose.yml with the following contents:

traefik:
image: traefik
command: --web --docker --docker.domain=docker.localhost --logLevel=DEBUG
ports:
- "80:80"
- "8080:8080"
- "443:443"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- /dev/null:/traefik.toml
machine:
image: jwilder/whoami
labels:
- "traefik.backend=web"
- "traefik.frontend.rule=Host:apps.192.168.1.11.nip.io"

Please change the Host above, mine is apps.192.168.1.11.nip.io. Yours will be different. If you are curious why do I have a weird host name like that, you can read more about it on: nip.io

Sidenote. Basically, apps.192.168.1.11.nip.io simply points to 192.168.1.11 which is my test machine. We need to use nip.io so we could test different route names. For example, I could use new-route.192.168.1.11.nip.io, though it still resolves to the same ip 192.168.1.11, Traefik would route us to a different container service.

Now let’s start the services.

sudo docker-compose up -d

This will start the Traefik server itself, plus a sample web server running on some random port which Traefik will route to. This web server simply prints out its container id, so we can test later if load balancing is also working.

Visit Traefik’s control panel at:

<your ip>:8080

You can test if your router is working by visiting the route we specified in traefik.frontend.rule in our docker-compose.yml. Mine is:

apps.192.168.1.11.nip.io

Traefik was able to know how to route this host by using the labels we specified in docker-compose.yml. Remember we specified the following:

labels:
- "traefik.backend=web"
- "traefik.frontend.rule=Host:apps.192.168.1.11.nip.io"

Now that our route is working, we could try to scale up our service.

docker-compose scale machine=2

Try refreshing the browser, you should see a different container id printed.

We could also deploy using docker commandline.

docker run -d --label traefik.backend=web2 --label traefik.frontend.rule=Host:cool.apps.192.168.1.11.nip.io jwilder/whoami

This is the usual docker run command except that we specified labels that Traefik can use.

Now we test it again, with our new route:

cool.apps.192.168.1.11.nip.io

That’s it. This is the most basic way to get started with Traefik.