Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load balance request traffic with muiltiple Node servers using NGINX

Tags:

node.js

nginx

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.

like image 759
Dan Kanze Avatar asked Jan 21 '26 21:01

Dan Kanze


1 Answers

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
like image 171
mak Avatar answered Jan 24 '26 16:01

mak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!