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.

  1. Create a file named Caddyfile on your host machine:

    localhost:80
    
    reverse_proxy caddy1:80 caddy2:80 {
        lb_policy round_robin
    }

    This tells Caddy to listen on localhost:80 and reverse proxy any incoming traffic to caddy1:80 and caddy2:80 using a round-robin strategy. This internal routing only works because we will place the load balancer on the same custom network.

  2. Start the load balancer container. We will expose it to the host on port 8880, attach it to the caddytest network, and mount our Caddyfile:

    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!