How to Setup Traefik Reverse Proxy for Docker Containers

How to Setup Traefik Reverse Proxy for Docker Containers. In this post, we introduce Traefik Proxy, its working principle, advantages then show you how to setup traefik reverse proxy for Docker containers.

What is Traefik Proxy?

Basically, Traefik is a modern HTTP reverse proxy and load balancer that inspects and configures microservice infrastructures automatically. With the help of this open source proxy server, developers easily handle containerized applications or programs. Apart from the dynamic configuration, it automates deployment across multiple environments and supports application scaling.

Some of them are Docker, Swarm, Kubernetes, Etcd, and Zookeeper are a few infrastructure components that work well with Traefik and help handle its configuration automatically and dynamically.

Further, it uses algorithms like round robin, IP Hash, and least connections to find new services and direct the traffic to the right container automatically. Also, it supports integration with a variety of backends to configure routing rules, SSL certificates, as well as service discovery.

With the help of this cloud native application proxy, developers simplify network complexities while deploying or designing applications. Unlike other traditional proxies, it handles large and complex deployments. Additionally, it comes with a potent collection of middleware’s that expand its functionalities to incorporate load balancing, API gateway, etc.

Every significant cluster technology is compatible with Traefik, which also has built in support for the leading distributed tracing and metrics suppliers. Consul, Nomad, etcd, docker, and Redis are a few providers and orchestrators.

How Does Traefik Proxy Work?

Well, Traefik Proxy is designed to work seamlessly with microservices and containerized applications by automatically discovering new services and routing traffic to the appropriate container. This is how the open source Traefik Proxy works:

  • At first, every inbound request is intercepted by Traefik, which then directs it to the appropriate backend services. Basically, you specify entry points when you launch Traefik (in their most basic forms). Following that, routers attached to these entry points examine the incoming requests to see if they comply with a set of guidelines. If they do, the router may modify the request before sending it to your services using bits of middleware.
  • Generates dynamic configuration based on the discovered services and their metadata. 
  • Traefik configures itself automatically from the services themselves using service discovery.
  • Updates its routing rules and load balancing algorithms based on the dynamic configuration.
  • Proxying traffic to the appropriate container based on the routing rules.

Advantages of Traefik Proxy

What is more, Traefik Proxy offers services auto discovery, distributed tracing (Zipkin, Jaeger, Open Tracing), and many other features that make it an ideal choice. But apart from these, Traefik Proxy offers several advantages over traditional load balancers and reverse proxies. Let us have a closer look at some of the main benefits of Traefik Proxy:

  • Quick deployments and easy management – With its support for dynamic configuration and seamless compatibility with containerized applications, the open source Proxy makes it simple to launch and control services across various environments as well as protocols in different clouds.
  • Supports Multiple backends – Allows integration with backends including Docker, Kubernetes, Consul, as well as ZooKeeper for managing routing rules and service discovery.
  • Flexible management – Supports major protocols and a wide range of customizable middlewares for load balancing, circuit breakers, authentication, and other functions for flexible management.

More Traefik Benefits

  • Offers SSL support – With the help of Let’s Encrypt, the cloud native proxy enables SSL termination. The feature allows it to automatically create and renew SSL certificates. Additionally, it offers custom certificates, authentication, automatic HTTPS, and many more options for strong security.
  • Delivers High performance – Designed with a focus on speed and performance, as a result, Traefik Proxy handles thousands of connections per second while still keeping a low latency.
  • API Gateway – If you use Treafik middlewares toolkit as a reverse proxy in front of API services, it helps to offload issues like authentication, SSL termination, as well as rate limiting.
  • Observability: The cloud native proxy has a clean and dynamic web UI as well as a built in dashboard that helps track traffic metrics in real time. 
  • Automated service discovery – Another benefit of Traefik Proxy is that it is easy to scale and eases the process of management by automatically discovering new services, and updating its routing policies as well as load balancing algorithms.

This is the main article part of How to Setup Traefik Reverse Proxy for Docker Containers. Let’s proceed. 

How to Setup Traefik Reverse Proxy for Docker Containers

Follow this post to show you how to set up Traefik reverse proxy for Docker containers.

Prerequisites

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

Install Docker and Docker Compose

The Docker package is available in the default repository of all major Linux distributions. However, it is recommended to install the Docker package from its official repository.

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

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

Next, download and add 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
				
			

After that, add the Docker repository to the APT file using 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
				
			

Next, update the repository and install Docker with the following command.

				
					apt update -y
apt install docker-ce docker-compose -y

				
			

After installing both packages, please verify the Docker installation using the following command.

				
					docker -v
				
			

See the Docker version in the following output.

				
					Docker version 23.0.1, build a5ee5b1
				
			

Setting Up Traefik Reverse Proxy

Equally, now you need to install the Apache utils package to create a user and password for authentication.

				
					apt install apache2-utils -y
				
			

After the installation, create an admin user and genearte a hashed password using the following command.

				
					htpasswd -nb admin Traefix_Secure_Password

				
			

You should see the generated hashed password in the following output.

				
					admin:$apr1$dIxCpX1V$r8sg6eID1DFFL94m9FaNa1
				
			

Next, create a directory for Traefik with the following command.

				
					mkdir project
				
			

Eventually, next create a Traefik configuration file inside the generated directory.

				
					cd project
nano traefik.toml
				
			

Define your Traefik API, docker, acme and Let’s encrypt SSL as shown below.

				
					[entryPoints]
  [entryPoints.web]
    address = ":80"
    [entryPoints.web.http.redirections.entryPoint]
      to = "websecure"
      scheme = "https"
  [entryPoints.websecure]
    address = ":443"

[api]
  dashboard = true
[certificatesResolvers.lets-encrypt.acme]
  email = "hitjethva@gmail.com"
  storage = "acme.json"
  [certificatesResolvers.lets-encrypt.acme.tlsChallenge]

[providers.docker]
  watch = true
  network = "web"

[providers.file]
  filename = "traefik_secure.toml"

				
			

Save and close the file then create another file to store the Traefik secrets.

				
					nano traefik_secure.toml
				
			

Add the following configuration.

				
					[http.middlewares.simpleAuth.basicAuth]
  users = [
    "admin:$apr1$dIxCpX1V$r8sg6eID1DFFL94m9FaNa1"
  ]

[http.routers.api]
  rule = "Host(`traefik.cloudinfrastructureservices.co.uk`)"
  entrypoints = ["websecure"]
  middlewares = ["simpleAuth"]
  service = "api@internal"
  [http.routers.api.tls]
    certResolver = "lets-encrypt"

				
			

Save and close the file when you are done. Follow by creating a Docker network using the following command.

				
					docker network create web
				
			

After that, verify the Docker network using the following command.

				
					docker network ls
				
			

See the following output.

				
					NETWORK ID     NAME      DRIVER    SCOPE
d1e09b506236   bridge    bridge    local
9ae5930ccebf   host      host      local
7dcf46a4ad28   none      null      local
dc098b33961a   web       bridge    local

				
			

Also, create a acme.json file and set proper permission with the following command.

				
					touch acme.json
chmod 600 acme.json

				
			

Once you are done, proceed to the next step.

Launch Traefik Container

At this point, Traefik configuration files are ready to create a container. Run the following command next to create a Traefik container.

				
					docker run -d \
   -v /var/run/docker.sock:/var/run/docker.sock \
   -v $PWD/traefik.toml:/traefik.toml \
   -v $PWD/traefik_secure.toml:/traefik_secure.toml \
   -v $PWD/acme.json:/acme.json \
   -p 80:80 \
   -p 443:443 \
   --network web \
   --name traefik \
    traefik:v2.4

				
			

You should see the following screen.

Verify the running container by running the following command.

				
					docker ps
				
			

You should see the status of Traefik container in the following output.

				
					CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS          PORTS                                                                      NAMES
1a08f7e5a3e5   traefik:v2.4   "/entrypoint.sh trae…"   39 seconds ago   Up 38 seconds   0.0.0.0:80->80/tcp, :::80->80/tcp, 0.0.0.0:443->443/tcp, :::443->443/tcp   traefik
				
			

Access Traefik Dashboard

Now, open your web browser and access the Traefik dashboard using the URL https://traefik.cloudinfrastructureservices.co.uk/dashboard/. You will be asked to provide username and password to access the Traefik.

Provide your admin username, password and click on the Sign in button. At this point, you should see the Traefik dashboard on the following screen.

Create a WordPress Container

Next, create a WordPress container and register it to Traefik proxy. So now, create a docker-compose.yml file to create a WordPress container.

				
					nano docker-compose.yml
				
			

Add the following configurations.

				
					version: "3"
networks:
  web:
    external: true
  internal:
    external: false

services:
  wordpress:
    image: wordpress:latest
    environment:
      WORDPRESS_DB_HOST: mysql:3306
      WORDPRESS_DB_USER: wpuser
      WORDPRESS_DB_PASSWORD: securepassword
      WORDPRESS_DB_NAME: wpdb
    labels:
      - traefik.http.routers.blog.rule=Host(`wp.cloudinfrastructureservices.co.uk`)
      - traefik.http.routers.blog.tls=true
      - traefik.http.routers.blog.tls.certresolver=lets-encrypt
      - traefik.port=80
    networks:
      - internal
      - web
    depends_on:
      - mysql

  mysql:
    image: mysql:latest
    environment:
      MYSQL_ROOT_PASSWORD: root@123#
      MYSQL_DATABASE: wpdb
      MYSQL_USER: wpuser
      MYSQL_PASSWORD: securepassword
    networks:
      - internal
    labels:
      - traefik.enable=false

				
			

Save and close the file then launch the WordPress container using the following command.

				
					docker-compose up -d
				
			

You should see the following screen.

Check the status of WordPress container, run the following command.

				
					docker-compose ps
				
			

See the container status on the following screen.

Next, go back to the Traefik dashboard and click on the HTTP routers. You should see your WordPress container on the following screen.

Now, use the https://wp.cloudinfrastructureservices.co.uk URL from the above screen. You should see the WordPress installation page on the following screen.

Finally you are able to finish the rest of the steps to use the WordPress website.  Thank you for reading How to Setup Traefik Reverse Proxy for Docker Containers. We shall now conclude. 

How to Setup Traefik Reverse Proxy for Docker Containers Conclusion

Concluding the article we are aware that Traefik Proxy is a modern and cloud native HTTP reverse proxy and load balancer that is designed for microservices and containerized applications. Furthermore that allows developers to easily handle containerized applications with Traefik. 

For example, it offers several advantages over traditional load balancers, including easy deployment and management, automatic service discovery, multiple backends support, SSL support, and high performance.

For that reason, it offers distributed tracing, supports multiple load balancing algorithms, and allows the performing of active health checks. For security benefit, it supports Let’s Encrypt, custom certificates, authentication, as well as automatic HTTPS. If you are managing microservices or containerized applications, Traefik Proxy assists to scale and manage your services seamlessly.

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.

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