7

I understand that I can use Nodes cluster module in order to create several workers all serving the same socket connection (example from docs):

var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.process.pid + ' died');
  });
} else {
  // Workers can share any TCP connection
  // In this case its a HTTP server
  http.createServer(function(req, res) {
    res.writeHead(200);
    res.end("hello world\n");
  }).listen(8000);
}

However, what if I instead of serving the same connection want each worker to run their own server, each listening on a separate port?

Steve Bennett
  • 114,604
  • 39
  • 168
  • 219
csvan
  • 8,782
  • 12
  • 48
  • 91
  • 1
    I think the main reason for cluster is to imply muti threading and to use system process effectively.. Like a single connection is shared with 4 process to balance load.. Try using child process for executing bunch of servers ( not tried just an idea) – Sathish Aug 02 '15 at 00:52
  • Why do you want to do this? It feels like an [XY problem](http://xyproblem.info/). – Aaron Dufour Aug 02 '15 at 01:16
  • @AaronDufour I am trying to loadbalance several `socket.io` instances. In the app that we are developing, the core unit of user grouping is an organisation, and I would like each organisation to have its own socket.io server with its own port. – csvan Aug 02 '15 at 07:38
  • @csvan I think you'll get better performance if all processes listen to all ports, so that each will be load-balanced, but I answered your question anyway. – Aaron Dufour Aug 02 '15 at 17:41

1 Answers1

7

You can pass environment variables to each child, allowing the master process to assign them ports:

var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  var pidToPort = {}; 
  var worker, port;
  for (var i = 0; i < numCPUs; i++) {
    port = 8000 + i;
    worker = cluster.fork({port: port});
    pidToPort[worker.process.pid] = port;
  }

  console.log(pidToPort);

  cluster.on('exit', function(worker, code, signal) {
    // Use `worker.process.pid` and `pidToPort` to spin up a new worker with
    // the port that's now missing.  If you do so, don't forget to delete the
    // old `pidToPort` mapping and add the new one.
    console.log('worker ' + worker.process.pid + ' died');
  }); 
} else {
  // Start listening on `process.env.port` - but first, remember that it has
  // been cast to a string, so you'll need to parse it.
  console.log(process.env.port);
}
Aaron Dufour
  • 17,288
  • 1
  • 47
  • 69
  • I wanted Nginx load balancer w/ upstream. It helped me a lot. But I am confused about which one is better?, Node.js own clustering or Nginx load balancer or another? – enxtur Oct 04 '18 at 07:27