Turn Any Server into a Load Balancer — No Extra Cost
Setting up a normal server as a load balancer can be very beneficial, as some cloud providers charge extra for their inbuilt load balancer.
Here is the simple architecture of what we are going to set up.
Just go through the above architecture, and you will understand properly.
Let’s see how to set up a load balancer.
Step 1: Buy a server that will act as a load balancer.
Step 2: Install Nginx on your server, which will act as a reverse proxy for your load balancer.
Step 3: Set up a .conf file for enabling the reverse proxy for transferring the request from the load balancer server to the main servers.
Go to — cd /etc/nginx/sites-available
create the new file with name “load-balancer.conf” you can use any name for this file.
Now, paste the below code with your server 1 and server 2 IP and domain pointed on the load balancer.
upstream backend {
least_conn;
server 0.0.0.0:3000; # Place your Server 1 IP on which your application is hosted with the port
server 0.0.0.0:3000; # Place your Server 2 IP on which your application is hosted with the port
}
server {
listen 80;
server_name raiyanmemon.in; # Your Load balancer pointed domain
location / {
proxy_pass http://backend;
}
}
Explanation of the above code:
Here when any request comes on raiyanmemon.in, it redirects to the server 1 or server 2 according to the load on the server.
least_conn — is the type of algorithm which is used for distributing traffic over the two servers. It transfers the request to the server with the lead connections.
Set your server one and server to Ip address.
Before adding the IP address with the port, please verify that your application is visible when we visit the IP address with the assigned post.
After the process is done, add the firewall so that only the load balancer can access your application via IP address and assigned port.
Step 4: Enable the newly created nginx file.
Run the below command to enable our load balancer file and restart the Nginx server.
sudo ln -s /etc/nginx/sites-available/load-balancer.conf /etc/nginx/sites-enabled/load-balancer.conf
//Restart the nginx server
sudo systemctl restart nginx
This is it. Test your setup by having a load testing on your domain, and you can notice that the request is transferring to server 1 and server 2 as per the load.
Have recommendations or thoughts? Feel free to share them in the comments!
Want to know more about me or get in touch? Visit my website.
Keep coding and exploring ❤️