Your First Load Balancer
Playground overview
Now that HAProxy is installed, it's time to configure your first load balancer.
Before we dive in, let’s review the lab environment you’ll be working in.
In this lesson—and most of the ones that follow—you’ll interact with several machines, each with a specific role:
- dev-machine – Your "local machine" used to do testing (i.e. send requests to HAProxy).
- loadbalancer – The machine where HAProxy will be configured.
- backends – Servers acting as backend services, listening to HTTP and SSH traffic on ports 80 and 22.
Network topology
To reflect a real-world setup, dev-machine cannot access the backends directly. All traffic must go through the load balancer.
Configuring your first load balancer
Go to the loadbalancer tab and create the following configuration file:
listen my_lb
bind :80
server backend-01 backend-01:80
server backend-02 backend-02:80
server backend-03 backend-03:80
Restart the service for the changes to take effect:
sudo systemctl restart haproxy
Switch to the dev-machine tab and try sending requests to the load balancer:
while true; do curl http://loadbalancer; sleep 2; done
You should see something like this:
Hello from backend-01!
Hello from backend-02!
Hello from backend-03!
Hello from backend-01!
Hello from backend-02!
Hello from backend-03!
🎉 Congratulations!
You've successfully configured your first load balancer using HAProxy.
Configuration breakdown
Let’s go through the configuration options one by one.
The listen
block tells HAProxy to listen on specified IP addresses and ports, and to forward incoming connections to a defined set of backends.
To specify which IP addresses and ports HAProxy should listen on, use the bind directive.
In this example, bind :80 tells HAProxy to listen on port 80 across all available network interfaces.
Here are a few other ways you can use the bind directive:
| Bind line | What it does |
|---|---|
bind 0.0.0.0:80bind :80 | Listen on all IP addresses assigned to this server at port 80. |
bind :80,:8080 | Listen on ports 80 and 8080. (No space between ports) |
bind :6379-6390 | Listen on all the ports between 6379 and 6390. |
Finally, the server directive tells HAProxy where to forward incoming traffic.
In this example, three backend servers are defined. HAProxy will forward each request to one of them, selected at random.
- Previous lesson
- Installation
- Next lesson
- HTTP vs TCP