Dan Kanze
Dan Kanze

Reputation: 18595

Load balance request traffic with muiltiple Node servers using 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.

Upvotes: 3

Views: 1435

Answers (1)

mak
mak

Reputation: 13405

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

Upvotes: 7

Related Questions