Below i document how to make a simple Load Balancer. This load balancer uses HAProxy and monitors the health of a server using a script. If the health of the server goes down, HAProxy Removes the Node from the “Cluster”.
Below is the HAProxy Config.
frontend http_front
bind *:80
default_backend http_back
backend http_back
balance roundrobin
http-check uri /status.php expect string OK
server <server1 name> <private IP 1>:80 check
server <server2 name> <private IP 2>:80 check
Below is the PHP Script running on the servers to give health stats.
<?php
// Get CPU usage
$load = sys_getloadavg();
$cpu_usage = $load[0];
// Get Memory usage
$mem_usage = memory_get_usage(true);
$mem_total = memory_get_usage(false);
$mem_percent = $mem_usage / $mem_total * 100;
// Test MySQL database connection
$mysqli = mysqli_connect("localhost", "username", "password", "database");
// Check if CPU usage is greater than 60%
if ($cpu_usage > 60) {
echo "FAIL\n";
}
// Check if Memory usage is greater than 80%
if ($mem_percent > 80) {
echo "FAIL\n";
}
// Check if there was an error connecting to the database
if (!$mysqli) {
echo "FAIL\n";
}
// If all tests pass, print OK
if ($cpu_usage <= 60 && $mem_percent <= 80 && $mysqli) {
echo "OK\n";
}
?>