Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Load Balance Server: Step-by-Step Setup Guide

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Load balancing distributes incoming traffic across multiple servers so no single machine gets overwhelmed. This improves responsiveness, ensures uptime during hardware failures, and lets you scale capacity by adding servers. Before you start, you need at least two backend servers (physical or virtual) running the same application, and one dedicated machine (or cloud instance) for the load balancer itself. This guide uses the open-source HAProxy as the balancer, but the concepts apply to Nginx, AWS ELB, or any similar tool.

What You'll Need

  • Two or more backend servers with your application installed and listening on a port (e.g., 8080).
  • A separate server for the load balancer (can be a small VM) with a public IP if serving external traffic.
  • SSH access to all servers.
  • Root or sudo privileges on the load balancer.
  • Optional: a domain name pointing to the load balancer's IP.

Step-by-Step

  1. Install HAProxy on the load balancer. On Ubuntu/Debian, run sudo apt update && sudo apt install haproxy. On CentOS/RHEL, use sudo yum install haproxy. Verify with haproxy -v.
  2. Configure HAProxy. Edit the main config file: sudo nano /etc/haproxy/haproxy.cfg. You'll replace the default content with your own frontend and backend sections.
  3. Define a frontend section. This tells HAProxy what to listen on. For HTTP traffic, add:
    frontend web_front
        bind *:80
        default_backend web_servers
    If you need HTTPS, add a line like bind *:443 ssl crt /etc/haproxy/certs/yourdomain.pem and adjust the backend accordingly.
  4. Define a backend section. List your backend servers with their IPs and ports. For two servers, add:
    backend web_servers
        balance roundrobin
        server web1 192.168.1.10:8080 check
        server web2 192.168.1.11:8080 check
    The check option enables health checks. Adjust IPs and ports to match your environment.
  5. Enable health checks (optional but recommended). Add an option httpchk line inside the backend to have HAProxy verify the HTTP response. For example: option httpchk GET /health. This ensures a server is removed from rotation if it fails.
  6. Save and test the configuration. Run sudo haproxy -c -f /etc/haproxy/haproxy.cfg to check for syntax errors. If it says 'Configuration file is valid', you're good.
  7. Start and enable HAProxy. Use sudo systemctl restart haproxy and then sudo systemctl enable haproxy to start on boot. Check status with sudo systemctl status haproxy.
  8. Test the load balancer. From your local machine, visit the load balancer's IP (or domain). Refresh several times; you should see responses from both backend servers (check your app's logs or a unique identifier). If you only see one server, check the health checks.
  9. Set up sticky sessions (if needed). If your app requires a user to stay on the same server (e.g., for session data), add cookie SERVERID insert indirect nocache in the backend and cookie web1 in each server line. This sets a cookie to route subsequent requests to the same server.
  10. Monitor and adjust. HAProxy provides a stats page. Add a listen stats section to your config:
    listen stats
        bind *:8404
        stats enable
        stats uri /stats
        stats auth admin:password
    Then access http://loadbalancer-ip:8404/stats with those credentials to see live traffic and server health.

Common Mistakes

  • Forgetting to open firewall ports. Ensure the load balancer allows incoming traffic on the ports you bind (e.g., 80, 443) and that backend servers allow traffic from the load balancer on their application port.
  • Misconfigured health checks. If your health check path returns a non-200 code (e.g., 404), HAProxy will mark the server as down. Test your health endpoint with curl first.
  • Using the same cookie name across different backends. This can cause session conflicts. Use unique cookie names per backend or per server.
  • Not testing failover. If you never simulate a server failure, you won't know if your health checks work. Stop one backend and see if traffic goes to the other.
  • Overlooking timeouts. Default timeouts may be too short for slow applications. Add timeout connect 5s, timeout client 30s, timeout server 30s in the defaults section to avoid dropped connections.

Tips

  • Use round-robin for even distribution unless you have heterogeneous servers; then consider 'leastconn' to send traffic to the least busy server.
  • Terminate SSL at the load balancer to reduce backend CPU load, but ensure backend connections are secure if they cross a network.
  • Keep configuration under version control. Store your haproxy.cfg in Git so you can track changes and roll back if needed.
  • Scale horizontally. When adding a new backend server, just add a line to the backend section and reload HAProxy (sudo systemctl reload haproxy) – no downtime.
  • Use a dedicated health check endpoint that checks database connectivity, not just a static file, to avoid routing traffic to a server that can't serve requests properly.

Troubleshooting

  • Nothing loads when accessing the balancer IP. Check HAProxy status: sudo systemctl status haproxy. If it's inactive, check the logs at /var/log/haproxy.log. Also verify the frontend bind port is listening: sudo netstat -tulpn | grep :80.
  • Only one server gets traffic. Check the stats page. If one server shows 'DOWN', your health check is failing. Test the health endpoint directly from the load balancer: curl http://backend-ip:port/health.
  • Error 503 Service Unavailable. This means all backend servers are down or the backend is misconfigured. Check the backend server IPs and ports, and ensure the servers are running.
  • Slow responses. Increase the timeouts in the defaults section. Also check backend server load – maybe they're genuinely overloaded.
  • Configuration changes not taking effect. Always run sudo systemctl reload haproxy (not restart) to apply changes without dropping connections. If you used restart, connections are dropped.
  • SSL errors. If using HTTPS, ensure your .pem file contains the full chain (certificate + intermediate + private key) and that file permissions are correct (readable by HAProxy).

Frequently Asked Questions

Q: Can I use a load balancer with just one backend server?
A: Yes, but it provides no redundancy. You'd only benefit from SSL termination or caching. For high availability, you need at least two.

Q: What's the difference between round-robin and leastconn?
A: Round-robin sends each new request to the next server in line, regardless of load. Leastconn sends to the server with the fewest active connections, which is better for long-lived connections like WebSockets.

Q: Do I need a dedicated load balancer machine?
A: Not necessarily. You can run HAProxy on one of your application servers, but that creates a single point of failure. A dedicated instance is recommended for production.

Q: How do I handle WebSockets with HAProxy?
A: HAProxy supports WebSockets by default. Ensure your timeout server is high enough (e.g., 1h) and use 'balance leastconn' to avoid uneven distribution.

Q: Can I load balance UDP traffic (e.g., DNS)?
A: Yes, HAProxy supports UDP with the 'udp' protocol in the frontend, but you must use a backend that supports UDP. For DNS, consider dedicated DNS load balancing.

Q: What happens when a backend server goes down?
A: HAProxy detects it via health checks and stops sending new traffic to it. Existing connections may be dropped unless you have session persistence and a backup server configured.