Skip to content

Instantly share code, notes, and snippets.

@devarajchidambaram
Last active January 23, 2018 05:11
Show Gist options
  • Save devarajchidambaram/ff5e8c07f6d0ad95eb9ae91d533135be to your computer and use it in GitHub Desktop.
Save devarajchidambaram/ff5e8c07f6d0ad95eb9ae91d533135be to your computer and use it in GitHub Desktop.
assign separate server/port to each worker?
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
var worker_id = '';
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
worker_id = '900'+i;
cluster.fork({port : worker_id});
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
console.log("App listening in ", process.env.port)
// Workers can share any TCP connection
// In this case it is an HTTP server
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(process.env.port);
console.log(`Worker ${process.pid} started`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment