Basics

Loadbalancing with Traefik #

When you built a containerized application, chances are that you want to deploy it for other people to use.

First off, there is a Docker network called public. This network is used by Traefik to route requests for a specific hostname to an individual container or Docker service.

In order to enable this for a service, we add the following:

version: '3.8'
services:
  example:
    image: wordpress
    networks:
      - public
    deploy:
      labels:
        traefik.enable: "true"
        traefik.docker.network: "public"
        traefik.port: "80"
        traefik.frontend.rule: "Host:wordpress.example.org"
networks:
  public:
    external: true
    name: public

The example labels enable ingress via Traefik. They instruct Traefik to route requests using the public network, to use port 80 on the container, and to use the hostname wordpress.example.org.

Once your stack is deployed, the first request to wordpress.example.org will trigger the SSL certificate setup via Let’s Encrypt and then we’re good to go! All you have to do is deploy the stack and visit your application in the browser — done.

For a complete example, please see our Wordpress example application.

Advanced Usage #

Traefik can also do more complex routing, add headers, use URL prefixes, and more - see the full list of traefik labels for details.

Some common examples:

Multiple Domains per Service #

traefik.enable: "true"
traefik.docker.network: "public"
traefik.port: "80"
traefik.frontend.rule: "Host:domain1.example.org,domain2.example.org"

Path Prefixes #

When the service listens for /some-prefix/...:

traefik.frontend.rule: "Host:example.org;PathPrefix:/some-prefix/"

When the service listens for / but you want it available under some prefix:

traefik.frontend.rule: "Host:example.org;PathPrefixStrip:/some-prefix/"

CORS headers #

Adding CORS headers to all responses returned by the service:

traefik.frontend.rule: "Host:api.example.org"
traefik.frontend.headers.customResponseHeaders:
  "Access-Control-Allow-Headers:*||Access-Control-Allow-Origin:my-origin.example.org"

HTTP Basic Authentication #

Create a htpasswd string like so:

$ echo $(htpasswd -nb user password) | sed -e s/\\$/\\$\\$/g
user:$$apr1$$UvokcOBp$$KFZ.XeQc6H.HNeKhLKw861

And then use it in traefik like so:

traefik.frontend.rule: "Host:behind-http-auth.example.org"
traefik.frontend.auth.basic.users: "user:$$apr1$$UvokcOBp$$KFZ.XeQc6H.HNeKhLKw861"

The $$ escaping is needed because single $ refer to environment variables.

Gain more insight #

By default the Traefik Dashboard is available on https://traefik.customer-name.customer.planetary-quantum.net. We password-protected the UI for you.

The dashboard allows you to see applications which are currently deployed behind it:

And, last but not least — it provides you with an overview about successful and failed requests: