Saturday, November 22, 2014

Configure Nginx for load balancing


Recently, in our project, I was asked to configure Nginx for load balancing as our app was becoming slow, owing to high traffic. I haven't worked much with Nginx, so I was a bit apprehensive at first. As it was Diwali holidays, nobody else was there in office and I had no choice. However, on fumbling around, it turned out to be much more easier than I had thought.

Imagine that you wish to run two different instances of your application to distribute the high traffic.
With Nginx, you can enable all requests to be proxied to your main domain, while Nginx takes care of distributing the requests to different servers in a round robin fashion.

Open the Nginx configuration file located at /etc/nginx/nginx.conf and add an upstream block and modify the server block as shown below: 

http {
    upstream yourapp {
        ip_hash;
        server domain1.com:8080;
        server domain2.com:8080;
    }

    server {
        listen 80;
        location / {
            proxy_pass http://yourapp;
        }
    }
}


That's it! Make sure your app is running on both the servers on your specified ports and then restart Nginx by running:
/etc/init.d/nginx restart

The ip_hash specified in the upstream block is used for session persistence so that subsequent requests of the same client can be directed to the same server. Nginx uses the client's ip address as a hash key to determine which server should be selected for the client's requests. Nginx also offers other options like weighted load balancing, least connected load balancing and health checks.


0 comments:

Post a Comment