Docker & Træfik – Loadbalancer made easy

Today in Docker. A scalable, nginx based, demo environment behind a loadbalancer in 26 lines and 2 commands.

We’ll be using Træfik and the Nginx based “whoami” container.

Get it

First of, let’s start with our Docker compose file:

version: '2'

services:
  proxy:
    image: traefik
    command: --web --docker --docker.domain=docker.localhost --logLevel=DEBUG
    networks:
      - webgateway
    ports:
      - "80:80"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - /dev/null:/traefik.toml

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

networks:
  webgateway:
    driver: bridge

Now, a little more detail, you create the URL that your server will be reachable with the “label” command on line 20:

labels:
      - "traefik.backend=whoami"
      - "traefik.frontend.rule=Host:whoami.docker.localhost"

This will create the service “whoami” in the loadbalancer and will make it accessible trough “whoami.docker.localhost”

Line 7 & 18 create the network and line 24-26 sets the properties.

Run it

Now, up it:

docker-compose up -d

And scale the service whoami:

docker-compose scale whoami=10

Now you can visit the loadbalancer on http://localhost:8080 or docker.localhost:8080 . This will look like:

After that, simply go to http://whoami.docker.localhost and you will get output similar to:

Hostname: 0ba96cbfa379
IP: 127.0.0.1
IP: ::1
IP: 172.18.0.31
IP: fe80::42:acff:fe12:1f
GET / HTTP/1.1
Host: whoami.docker.localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
X-Forwarded-For: 172.18.0.1
X-Forwarded-Host: whoami.docker.localhost
X-Forwarded-Proto: http
X-Forwarded-Server: 66978d8364ac

Now, every time you refresh the Hostname and IP should change ( because the loadbalancer is redirecting you to another instance.

And that’s it.

#5985 +(44) [X]

<Foggi> french are good for 2 things
<Foggi> art
<Foggi> and surrendering

Leave a Reply