Configuring the Load Balancer
Now that we have two application servers (caddy1 and caddy2) working properly on our custom bridge network, let’s create a load balancer that routes network requests between the two using a round-robin strategy!
Caddy works great as a file server, but it also functions excellently as a load balancer and reverse proxy.
Setting up a Caddyfile
To use Caddy as a load balancer, we need to create a custom configuration file called a Caddyfile.
-
Create a file named
Caddyfileon your host machine:localhost:80 reverse_proxy caddy1:80 caddy2:80 { lb_policy round_robin }This tells Caddy to listen on
localhost:80and reverse proxy any incoming traffic tocaddy1:80andcaddy2:80using a round-robin strategy. This internal routing only works because we will place the load balancer on the same custom network. -
Start the load balancer container. We will expose it to the host on port
8880, attach it to thecaddytestnetwork, and mount ourCaddyfile:docker run -d --network caddytest -p 8880:80 -v $PWD/Caddyfile:/etc/caddy/Caddyfile caddy
Testing the Load Balancer
Now, send requests to the load balancer:
curl http://localhost:8880/
Run this command multiple times. You should see the response alternate between “Hello from server 1” and “Hello from server 2”. Your single load balancer is successfully distributing traffic across your backend servers!