Balance two web servers with HAProxy and a real health check
Task
Put HAProxy in front of two small web servers, balance requests between them with round robin, and add a health check that requests a page rather than just opening a port. Break one server's page while leaving the port open, and prove the load balancer stops sending it traffic -- the failure a port check would miss.
Steps
- Configure nginx on lin-srv to listen on port 8080 and on lin-b on port 80, each serving
/with its own hostname and/healthreturningok. - Configure HAProxy on lin-srv to listen on port 80, with a backend of both servers,
balance roundrobin, andoption httpchk GET /healthwithcheckon each server. Save the configuration tolab/lb/haproxy.cfg. - From win-srv or the host, request
http://192.168.56.10/twenty times and save the responses tolab/lb/round-robin.txt. - On lin-b, make
/healthreturn a 500 error while nginx keeps running on port 80. Wait until HAProxy marks it down -- three failed checks, about six seconds at the defaults -- then request the page twenty times again and save the responses tolab/lb/one-down.txt. - Record in
lab/lb/checks.txtwhat a TCP-only check would have done in the previous step, and why.
Verify
These checks run in a POSIX shell: Terminal on macOS or Linux, and on Windows Git Bash (it comes with Git for Windows) or WSL. A stock Windows PowerShell or Command Prompt has no awk or grep, so there the first line fails.
grep -c 'httpchk' lab/lb/haproxy.cfg
sort lab/lb/round-robin.txt | uniq -c
sort lab/lb/one-down.txt | uniq -c
grep -Eic 'port|tcp|still|open' lab/lb/checks.txt
The round-robin responses split roughly evenly between the two hostnames. After lin-b's health page failed, every response comes from lin-srv. A TCP check would have seen port 80 open and kept sending half the users to a server returning errors.
Notes
HAProxy's statistics page, enabled with a stats section, shows each server's state and the result of its last check, and is the first place to look when a pool member is unexpectedly out of rotation.
This is an independent study companion for CompTIA Server+ SK0-005 and is not produced by or endorsed by CompTIA.