Load balancing using Nginx


min read

nginx load balancer


 We know Load balancing is a technique used for distributing network traffic across various servers.The reason behind this is to reduce the work load on a single server, ie switching among multiple server gives less load on each one and thus processing speed also improves by quick application responsiveness.There are so many ways to acquire, Round Robin Method,Least Response Time Method,Least Connection Method are some algorithms.We have software and hardware load-balancers,software provides an additional capability security.


  • Nginx
  • 3 CentOS 7

Setting up the environment

Installing nginx

I am using three centos server so these are steps for centos.

Install the extra packages repository

sudo yum install epel-release
Update the repositories and install Nginx
sudo yum update
sudo yum install nginx

After that you have setup the server blocks for each server for that

cd etc/nginx/

enter into sites-available folder and create a file name vhost.conf and save.Then do this

sudo ln -s /etc/nginx/sites-available/vhost.conf /etc/nginx/sites-enabled/vhost.conf

This line is used to enable the server-blocks.then restart nginx.

sudo systemctl restart nginx

Setting up load balancer

I have three servers and i need to configure load balancer on any of them,Before that you need to get the private ips of each server,for this

ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//'

we get the private ip in the second line.Then you need to create a file loadbalancer.conf at /etc/nginx/conf.d

sudo nano /etc/nginx/conf.d/load-balancer.conf

http {
   upstream api {
      server;      //replace with your server private ips

   server {
      listen 80; 

      location / {
           proxy_pass http://api;

here by default it uses round-robin method for switching server. We can change by configuring the file loadbalancer.conf, for eg, Least connections based load balancing, here server is selected by least active connections at that time.For this we have change in the top, put least_conn

upstream api {

We can also specify weights that highest weighted is selected the most often.

upstream api {
   server weight=4; 
   server weight=1;

Here the first server will choose often.the reason why its used is the available resources of servers are not equal.

Disable the default server configuration

We have to disable the default server block and point to loadbalancer.In ubuntu/debain based system we remove the default file from /etc/nginx/sites-enabled , in centos we just rename the file that is not ended with .conf.ie,

sudo mv /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf.isdisabled

Thats all about configuring loadbalancer using nginx.

Leave a Reply

Your email address will not be published. Required fields are marked *