Load Balancers: A Guide to Scaling Applications
Load Balancer:
How Does a Load Balancer?Work:
Round Robin (Default in NGINX)
Least Connections
IP Hash
Weighted Load Balancing
Setting Up NGINX as a Load Balancer:
Step 1: Install NGINX
If NGINX is not installed, run:
sudo apt update
sudo apt install nginx -y
Step 2: Configure NGINX for Load Balancing
Open the NGINX configuration file:
sudo nano /etc/nginx/nginx.conf
Replace or modify the content as follows:
领英推荐
http {
upstream backend_servers {
server 192.168.1.101; # Backend Server 1
server 192.168.1.102; # Backend Server 2
server 192.168.1.103; # Backend Server 3
}
server {
listen 80;
location / {
proxy_pass https://backend_servers;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
Step 3: Restart NGINX
Save the file and restart NGINX to apply changes:
sudo nginx -t # Test configuration
sudo systemctl restart nginx
Step 4: Verify Load Balancing
Send multiple requests using curl or a browser:
curl https://localhost
Each request should return a response from a different backend server, confirming that load balancing is working.
Advanced Load Balancing with NGINX
If you want to use Least Connections, update your config like this:
upstream backend_servers {
least_conn;
server 192.168.1.101;
server 192.168.1.102;
server 192.168.1.103;
}
To use Weighted Load Balancing (if some servers are more powerful)
upstream backend_servers {
server 192.168.1.101 weight=3;
server 192.168.1.102 weight=1;
server 192.168.1.103 weight=2;
}
Conclusion:
Load balancers are essential for building highly available, fault-tolerant, and scalable applications. NGINX makes it easy to distribute traffic among multiple servers efficiently.
?? Round Robin is simple and effective for evenly distributing traffic.
?? Least Connections is ideal when requests have varying processing times.
?? Weighted Load Balancing lets you allocate traffic based on server capacity.
For production environments, consider NGINX Plus, HAProxy, AWS ELB, or GCP Load Balancers for better performance and health monitoring.