Search code examples
node.jsipcpm2

How can we configure master process when using PM2


I have an problem with PM2 in NodeJS. Without PM2, we always have some lines of code like below to configure master process

if(cluster.isMaster){
    //master process configuration
} else {
    //worker process configuration
}

Exactly, I want to send message from a worker to master, then, master will send back a message to all workers for notification an event.

Actually, I saw that, no lines of code in master process configuration runs when using PM2.

Many thanks for any idea about this issue !


Solution

  • With PM2, you usually don't have to use this constuction. Typically, it looks like the following:

    var cluster = require('cluster');  
    var http    = require('http');  
    var os      = require('os');
    var numCPUs = os.cpus().length;
    
    if(cluster.isMaster){
      for (var i = 0; i < numCPUs; ++i) {
        cluster.fork();
      }
    } else {
      http.createServer(function(req, res) {
        res.writeHead(200);
        res.end("hello world");
      }).listen(8080);
    }
    

    With PM2 the equivalent for the above is:

    var http = require('http');
    
    http.createServer(function(req, res) {  
      res.writeHead(200);
      res.end("hello world");
    }).listen(8080);
    

    pm2 start app.js -i <number of instances>

    you can read up more on the topic here

    Update: You can try to distinguish between master and slave by passing command line arguments. Here is an example ecosystem.json:

    {
      "apps" : [
        {
          "name": "Master",
          "script": "app.js",
          "args": ["master"],
          "instances": "1",
        },
        {
          "name": "Slave",
          "script": "app.js",
          "args": ["slave"],
          "instances": "3"
        }
      ],
    ...
    

    Then you can do the following:

    argv = process.argv.slice(2) //stripe 'node', 'app.js' away
    
    if (argv[0] === 'master'){
       // ...
    } else {
      // ...
    }