How to Setup Traefik Load Balancer for Docker Containers

How to Setup Traefik Load Balancer for Docker Containers. In this post, we introduce Traefik Load Balancer, its advantages then show you how to setup Traefik Load Balancer for Docker Containers.

Firstly,Traefik load balancer is a  renowned dynamic reverse proxy and load balancer. A cloud native, open source system that divides network traffic among a number of servers or containers. Designed to make it simpler to deploy cloud native apps that are based on microservices. The user interface, scalability, and advanced features of Traefik had recently helped it become more well liked among developers. Let’s learn more about its features and advantages.

What is Traefik Load Balancer and How It Works

Discovering Dynamic Services

Above all, Traefik is designed to be dynamically configured according to the state of the cluster at any given time. Consul, Zookeeper, the Kubernetes API, and Docker labels are just a few of the service discovery tools it uses to find new services, and it then routes traffic accordingly.

Routing

Consequently, Traefik carries out complex routes based on variables like the URL path, HTTP headers, and SSL certificates. Moreover, it supports routing protocols, including PathPrefix, Host, and Headers.

It also assists canary deployments only by sending a small portion of traffic to a test version of a service.

Load balancing

What is more, Traefik evenly distributes incoming traffic among the available containers using a variety of load balancing methods, including round robin, least connections, and IP hash.

Provides session affinity guarantees that a client’s following requests are always forwarded to the same container.

Scalability

The tremendous scalability of Traefik allows it to process thousands of requests per second. It scales horizontally when a cluster’s container count grows.

Then, Traefik automatically detects these changes and modify the routing, once it detects new containers are added to or withdrawn from a cluster.

Management and Monitoring

Moreover, Traefik provides its users with access to a web based dashboard that makes it simple to track and control their traffic. Real time analytics including requests per second, response times, and error rates are shown on the dashboard. Also integrates with a range of monitoring and alerting technologies, including Prometheus and Grafana, etc 

Cloud Native Support

Besides, Traefik is cloud native and several cloud service providers, including AWS, Azure, and Google Cloud, allow for its deployment. Traefik easily integrates with other cloud native applications like Istio, Linkerd, and Envoy.

Advantages of Traefik Load Balancer

Simple to Use

One of the prime benefits of Traefik is the easiness to set up and how it operates with a simple configuration syntax and an intuitive web based interface. Supports several languages and frameworks and is created while keeping professionals in mind.

Flexible Configuration

Equally, Traefik easily finds new services and change its route without the need for human intervention due to its dynamic setup. Quite versatile and works well in dynamic settings like cloud native apps.

High Availability

Above all, Traefik is highly available and guarantees traffic is routed due to its advanced features, even if any of the cluster’s nodes fail. By doing so downtime is reduced and the functionality of the apps is maintained.

Scalability

Basically, Traefik is incredibly scalable with support for horizontal scaling as a cluster’s number of containers grows. And, works well with large applications as it handles thousands of requests per second.

Security

Further, Traefik provides security measures including SSL termination, client certificate authentication, and rate limiter. Integrates with additional security tools like Keycloak, OAuth2, and Let’s Encrypt.

Cloud Native Compatibility

Designed to integrate with container orchestration systems. Furthermore, it is set up on several cloud service providers, including AWS, Azure, and Google Cloud.

Community Support and Open Source

Even more, Traefik is open source and has a wide and active community of developers and contributors. This implies it is regularly updated and enhanced, with the addition of new features and bug fixes.

Next section explains How to Setup Traefik Load Balancer for Docker Containers.

How to Setup Traefik Load Balancer for Docker Containers

Prerequisites

  • A server running the Linux operating system.
  • A root user or a user with sudo privileges.

Getting Started

Before starting, you need to update and upgrade all the system packages to the latest version. You update them by running the following command.

				
					apt update -y
apt upgrade -y
				
			

After updating all the packages, you proceed to the next step.

Add Docker Repository

By default, the Docker package is available in the Ubuntu default repository. However, it is a good idea to install the latest version of Docker from Docker’s official repository.

First, install all the required dependencies using the following command.

				
					apt install apt-transport-https ca-certificates curl software-properties-common
				
			

Next, download and import the Docker GPG key with the following command.

				
					curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
				
			

Then, add the Docker repository to the APT with the following command.

				
					echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null

				
			

Once the repository is added, you update the repository cache with the following command.

				
					apt update
				
			

Install Docker and Docker Compose

Now, you install both Docker and Docker Compose packages by running the following command.

				
					apt install docker-ce docker-compose
				
			

After the successful installation, you verify the Docker installation using the following command.

				
					docker version
				
			

You should see the Docker version information on the following screen.

To check the Docker active status, run the following command.

				
					systemctl status docker
				
			

Once you are finished, you proceed to the next step.

Configure Traefik Load Balancer

Here at first, create a Docker network using the following command.

				
					docker network create web_zone
				
			

Now, you verify the network with the following command.

				
					docker network ls
				
			

You should see the following screen.

verify docker network

Create a directory for the Traefik project using the following command.

				
					mkdir traefik
				
			

Navigate to the project directory and create a traefik.yaml file.

				
					cd traefik
nano traefik.yaml

				
			

Add the following configuration.

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

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

				
			

Save and close the file when you are done. Then, create another file to define the provider information.

				
					nano tls.yaml
				
			

Add the following configuration.

				
					http:
    routers:
        http_router:
            rule: "Host(`traefik.cloudinfrastructureservices.co.uk`)"
            service: allbackend
        https_router:
            rule: "Host(`traefik.cloudinfrastructureservices.co.uk`)"
            service: allbackend
            tls:
                certResolver: myresolver
                options: tlsoptions
    services:
        allbackend:
            loadBalancer:
                servers:
                    - url: "http://myserver1/"
                    - url: "http://myserver2/"
           
tls:
    options:
        tlsoptions:
            minVersion: VersionTLS12

				
			

Save the file then create a file to store the Let’s Encrypt certificate.

				
					touch acme.json
				
			

Set proper permission on the file.

				
					chmod 600 acme.json
				
			

Create a Docker Compose File for Traefik

Here at this step you need to create a docker-compose.yaml file to launch the Traefik container. You create it in the same directory using the following command.

				
					nano docker-compose.yml
				
			

Add the following configuration.

				
					version: '3'

services:

  traefik:
    image: traefik:latest
    command: --docker --docker.domain=cloudinfrastructureservices.co.uk
    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

				
			

Save and close the file when you are done.

Configure Backend Server

Please create two backend servers using Nginx. First, create a directory to store all configurations.

				
					mkdir ~/traefik/backend
				
			

Following that step, please navigate to the directory and create two files to identify both servers.

				
					cd ~/traefik/backend
echo "<h1> First Web Server</h1>" > index-server1.html
echo "<h1> Second Web Server</h1>" > index-server2.html

				
			

Then, create a docker-compose.yml file to run Nginx containers.

				
					nano docker-compose.yml
				
			

Add the following configuration.

				
					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

				
			

Save and close the file when you are finished.

Launch the backend Servers

At this point, all the configurations are ready. Now create Nginx containers using the following command.

				
					cd ~/traefik/backend
docker compose up -d
				
			

This downloads the Nginx Docker images from the Docker repository and create two containers as shown below.

Now verify the status of both Nginx containers using the following command.

				
					docker-compose ps
				
			

If everything is fine, you should see the following screen.

verify nginx container

Launch Traefik Container

Navigate to the Traefik directory and start the Traefik container using the following command.

				
					cd ~/traefik
docker compose up -d
				
			

You should see the following screen.

Verify the active status of the Traefik container using the following command.

				
					docker-compose ps
				
			

You should see the following screen.

Verify Traefik Load Balancing

At this point, Traefik is installed and configured to load balancing both Nginx web servers. Now, it’s time to test it.

Open your web browser and type the URL https://traefik.cloudinfrastructureservices.co.uk. You should see your first Nginx page on the following screen.

Refresh the page. You should see the second Nginx page on the following screen.

Thank you for reading How to Setup Traefik Load Balancer for Docker Containers. We shall conclude the article now. 

How to Setup Traefik Load Balancer for Docker Containers Conclusion

Finally, Traefik is created with the user’s needs in mind with an easy configuration file format and a web based dashboard. It also enables users to conveniently monitor and is known as a powerful and flexible tool for managing traffic in cloud native environments making it a popular choice for many organizations.

Avatar for Hitesh Jethva
Hitesh Jethva

I am a fan of open source technology and have more than 10 years of experience working with Linux and Open Source technologies. I am one of the Linux technical writers for Cloud Infrastructure Services.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x