Bobcares

Docker compose traefik loadbalancer | Explained

by | Sep 2, 2022

This ultimate guide will teach you how to attach labels to your containers, route traffic, and load balance with Traefik and Docker. As a part of Docker support services, Bobcares support team has created an article about Docker compose traefik loadbalancer.

Docker compose traefik loadbalancer

 

Traefik is having four main concepts: Entry point, router, middleware, and service.

 

You can configure it to listen on certain entry points like ports, for example, TCP/HTTP on port 80. Then the incoming request has to match to a route, each request can go through middleware or a couple of them – ex. path rewrite, compression, etc.

 

Finally, reach a configured service that was assigned to the matched route as a result the services will map to your app web server.

 

A few common use-cases for the reverse proxy to a docker/docker-compose configs are:

 
  • Routing inbound traffic to the multi-container environments, i.e to  route the request to the web servers.
 
  • Terminate SSL.
 
  • To allow load balancing in multiple backend servers environments.
 
  • Basic authentication.
 
  • IP whitelisting/blacklisting.
 

Eventually, reverse proxy sits in front of the application and can terminate the SSL, it then route the client requests to the correct backend web servers.

 

Docker compose traefik loadbalancer

 

Using a reverse proxy you can even split incoming traffic onto multiple servers, all working inside an internal network and exposed under a single public IP address.

 

Configure Traefik load balancer with Docker in Ubuntu

 

Requirements:

 
  • Installed docker and docker-compose
 
  • Docker images.
 
  • DNS “A” record to map your domain i.e to get a Let’s Encrypt certificate, for example, “traefik.domain.com”
 

Configuration

 

We will be now taking two backend servers (Nginx container) and one Traefik container in the same Docker network zone. You have to add your domain instead “traefik.domain.com”.

 

Let’s begin by creating a directory in your home location.

 
$ mkdir traefik && cd traefik
 

Now create a docker network using the below command, this helps to reach the container from their name.

 
$ docker network create web_zone
 

Traefik.yaml configuration

 

Firstly, create a file named “traefik.yaml” and paste the following content:

 
# Static configuration
entryPoints:
    unsecure:
        address: :80
    secure:
        address: :443

certificatesResolvers:
    myresolver:
        acme:
            email: admin@domain.com
            storage: acme.json
            httpChallenge:
                entryPoint: unsecure      
providers:
      file:
      filename: tls.yaml
      watch: true
 

From the above code, the entry Points are the front-end listing with services and ports. certificatesResolvers is to use an on-demand Letsencrypt certificate and the Providers are the file to define routers or middlewares services.

 

File configuration

 

Now, in the same directory create one more file “tls.yaml” that we have defined in the provider section and paste the given 0yaml configuration as shown:

 
>http:
    routers:
        http_router:
            rule: "Host(`traefik.yourdomain.com`)"
            service: allbackend
        https_router:
            rule: "Host(`traefik.domain.com`)"
            service: allbackend
            tls:
                certResolver: myresolver
                options: tlsoptions
    services:
        allbackend:
            loadBalancer:
                servers:
                    - url: "http://server1/"
                    - url: "http://server2/"          
tls:
    options:
        tlsoptions:
            minVersion: VersionTLS12
 

Further, create the following file to store the Let’s Encrypt certificate:

$ touch acme.json
$ chmod 600 acme.json
 

Docker-compose for traefik

 

Additionally, create a container using docker-compose and map to 80, 443 ports, define your domain name, and create a file docker-compse.yml:

 
$ vim docker-compose.yml

later paste the following configuration:

 
version: '3'
services:

  traefik:
    image: traefik:latest
    command: --docker --docker.domain=yourdomain.com
    ports:
      - 80:80
      - 443:443
    networks:
      - web_zone
    volumes:
      - /run/docker.sock:/run/docker.sock
      - ./traefik.yaml:/traefik.yaml
      - ./tls.yaml:/tls.yaml
      - ./acme.json:/acme.json
    container_name: traefik
    restart: always
networks:
  web_zone:
      external: true
 

Backend server

 

Let’s run two backend servers using Nginx image. Make a directory for this:

$ mkdir ~/traefik/backend && cd ~/traefik/backend/

 

Create two index files as below.

 
echo "<h1> Hello server 1</h1>" > index-server1.html
 
echo "<h1> Hello server 2/h1>" > index-server2.html
 

Docker compose file to run on two Nginx backend servers

 

The following is the simple compose file that makes two Nginx containers. Create a docker-compse.yml file and paste the following code:

version: '3'
services:
  myserver1:
    image: nginx
    container_name: nginx1
    restart: always
    volumes:
      - ./index-server1.html:/usr/share/nginx/html/index.html
    networks:
      - web_zone
  myserver2:
    image: nginx
    container_name: nginx2
    restart: always
    volumes:
      - ./index-server2.html:/usr/share/nginx/html/index.html
    networks:
      - web_zone
networks:
  web_zone:
        external: true
 

You need to start the Docker by running the container. First up the Nginx backend container by using the command:

 
:~/traefik/backend$ docker compose up -d
 

Two containers must be running, and this can be confirmed from the command:

 
:~/traefik/backend$ docker ps
 

Now, go back to the directory and run traefik load balancer.

 
:~/traefik$ docker compose up -d
 

Make sure the traefik container is up and running fine.

 
:~/traefik$ docker ps
 

Browse the site

 

Open a browser and type your domain name http://traefik.domain.com. Page will display as “Hello server1“.

echo "< h1 > Hello server 1< /h1 >" > index-server1.html

Likewise, if you refresh the page next will be routed to the second backend page. This is called as default routing algorithm in traffic.

echo "< h1 > Hello server 2< /h1 >" > index-server1.html

You can also check that the certificate is issued by Letsencrypt while the container is up. Just access it with HTTPS before the link” https://traefik.domain.com”

[Need assistance with similar queries? We are here to help]

 

Conclusion

 

Traefik Reverse Proxy or Load Balancer has an open-source Edge Router which made to deploy services with an easy convenient model. To conclude from this article, You learned how to use Docker compose traefik load balancer for your docker container.

 

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Never again lose customers to poor
server speed! Let us help you.

Privacy Preference Center

Necessary

Necessary cookies help make a website usable by enabling basic functions like page navigation and access to secure areas of the website. The website cannot function properly without these cookies.

PHPSESSID - Preserves user session state across page requests.

gdpr[consent_types] - Used to store user consents.

gdpr[allowed_cookies] - Used to store user allowed cookies.

PHPSESSID, gdpr[consent_types], gdpr[allowed_cookies]
PHPSESSID
WHMCSpKDlPzh2chML

Statistics

Statistic cookies help website owners to understand how visitors interact with websites by collecting and reporting information anonymously.

_ga - Preserves user session state across page requests.

_gat - Used by Google Analytics to throttle request rate

_gid - Registers a unique ID that is used to generate statistical data on how you use the website.

smartlookCookie - Used to collect user device and location information of the site visitors to improve the websites User Experience.

_ga, _gat, _gid
_ga, _gat, _gid
smartlookCookie
_clck, _clsk, CLID, ANONCHK, MR, MUID, SM

Marketing

Marketing cookies are used to track visitors across websites. The intention is to display ads that are relevant and engaging for the individual user and thereby more valuable for publishers and third party advertisers.

IDE - Used by Google DoubleClick to register and report the website user's actions after viewing or clicking one of the advertiser's ads with the purpose of measuring the efficacy of an ad and to present targeted ads to the user.

test_cookie - Used to check if the user's browser supports cookies.

1P_JAR - Google cookie. These cookies are used to collect website statistics and track conversion rates.

NID - Registers a unique ID that identifies a returning user's device. The ID is used for serving ads that are most relevant to the user.

DV - Google ad personalisation

_reb2bgeo - The visitor's geographical location

_reb2bloaded - Whether or not the script loaded for the visitor

_reb2bref - The referring URL for the visit

_reb2bsessionID - The visitor's RB2B session ID

_reb2buid - The visitor's RB2B user ID

IDE, test_cookie, 1P_JAR, NID, DV, NID
IDE, test_cookie
1P_JAR, NID, DV
NID
hblid
_reb2bgeo, _reb2bloaded, _reb2bref, _reb2bsessionID, _reb2buid

Security

These are essential site cookies, used by the google reCAPTCHA. These cookies use an unique identifier to verify if a visitor is human or a bot.

SID, APISID, HSID, NID, PREF
SID, APISID, HSID, NID, PREF