Nginx as load balancer

This article explains, how to use nginx as load balancer and also gives an example

Hello all. Today we will see how to use nginx as load balancer. First of all how to get nginx on your machine

sudo apt-get install nginx

windows users for installation refer here

what is load balancing?
In short terms , the traffic for your website/app spliced across multiple app/servers.
In technical terms requests to your app/this server are handled across multiple app/servers.

Hope you are having a working nginx on your machine. To check nginx installed on your machine type
 nginx -v this shows version of the nginx installed like this  nginx version: nginx/1.11.0

Now we have to write the conf file to nginx act as a load balancer.

The question is where to write?
    We need to understand the directory structure of nginx. 

 nginx --|
               --- sites-enabled/
             --- sites-available/
             --- conf.d/
             --- lot-more-directories

we need to write the config in  sites-enabled/ directory.

But the best practice is to write config file in  sites-available and then create symbolic link to  sites-enabled.

so the default conf for load balancing is:

 http {
upstream myapp1 {

server {
listen 80;

location / {
proxy_pass http://myapp1;

Here the default method for load balancing is  RoundRobin.

In the example configuration myapp1 is running in three instances. So the requests to the myapp1 is distributed across three servers(srv1 - srv3).

Make sure you replace with your server names.

Now Put this config into  sites-available directory named loadbalance.conf

Create symblink by this command

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

Note: Always use absolute path . don’t use relative path like this sudo ln -s loadbalance.conf /etc/nginx/sites-enabled/ — this will not work . Always use absolute path.

After creating symblink restart the nginx server.

In ubuntu 14.04 ---> sudo service nginx restart

In ubuntu 16.04 --->  sudo systemctl restart nginx.service

Now you can check all of your three servers logs to check requests are coming .

Hope this helps. 

Leave a comment

(Note: Comments are moderated)