Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Load balance request traffic with muiltiple Node servers using NGINX

Load balance request traffic with muiltiple Node servers using NGINX

Problem

According to this answer:

You should run multiple Node servers on one box, 1 per core and split request traffic between them. This provides excellent CPU-affinity and will scale throughput nearly linearly with core count.

Got it, so let's say our box has 2 cores for simplicity.

I need a complete example a Hello World app being load balanced between two Node servers using NGINX.

This should include any NGINX configuration as well.

Problem courtesy of: Dan Kanze

Solution

app.js

var http = require('http');
var port = parseInt(process.argv[2]);

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(port);

console.log('Server running at http://localhost:' + port + '/');

nginx configuration

upstream app  {
  server localhost:8001;
  server localhost:8002;
}

server {
  location / {
    proxy_pass  http://app;
  }
}

Launch your app

node app.js 8001
node app.js 8002

HttpUpstreamModule documentation

Additional reading material

  • cluster module - still experimental, but you don't need nginx
  • forever module - in case your app crashes
  • nginx and websockets - how to proxy websockets in the new nginx version
Solution courtesy of: mak

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Load balance request traffic with muiltiple Node servers using NGINX

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×