a blog for those who code

Tuesday, 15 September 2015

Configuring Nginx as Load Balancer in NodeJS

In this post we are going to discuss about configuring nginx as load balancer in NodeJS. In our previous post we have described the way of doing load balancing in NodeJS, in which one way was using nginx. Nginx can load balance and distribute user sessions to multiple nodes if your application has several instances.

According to nginx.org, nginx has one master process and several worker processes. The main purpose of the master process is to read and evaluate configuration, and maintain worker processes. Worker processes do actual processing of requests. nginx employs event-based model and OS-dependent mechanisms to efficiently distribute requests among worker processes. The number of worker processes is defined in the configuration file and may be fixed for a given configuration or automatically adjusted to the number of available CPU cores.

At first we will set up nginx as per our requirements. The first thing is to set up an upstream block in nginx.conf file to define the nodes in an upstream block.

upstream forNodeJS {
  server 127.0.0.1:7000;
  server 127.0.0.1:7001;
}

You can also include a weight parameter on the server directive to set the proportion of traffic to be directed to it. For example server 127.0.0.1:7000 will receive 2 times more sessions than 127.0.0.1:7001.

upstream forNodeJS {
  server 127.0.0.1:7000 weight=2;
  server 127.0.0.1:7001;
}

The above configuration actually means that we have two node.js server processes in port 7000 and 7001 and both of them will be doing the same work. Nginx is useful for horizontal scaling as well i.e. adding many servers as the upstream processes like above can be on different machines. Along with that you can also set up SSL Termination with Nginx (Nginx keeps SSL certificates with itself and it will talk to Node.js processes over HTTP).

Now we will create our node.js server as :

var http = require('http');
http.createServer(function(req, res) {
  console.log("Port 7000")
  res.writeHead(200);
  res.end("Hello Nginx in NodeJS");
}).listen(7000, "127.0.0.1");

http.createServer(function(req, res) {
  console.log("Port 7001")
  res.writeHead(200);
  res.end("Hello Nginx in NodeJS");
}).listen(7001, "127.0.0.1");

After the above configurations of nginx is done you can start the nginx server using the command nginx start. Then you need to run the above file using node command. Now when you hit http://127.0.0.1 we will get for the first time Port 7000 then Port 7001 in our console respectively as Nginx follows Round-Robin mechanism.

Please Like and Share CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment