How can we set up the master process when using PM2

I have a problem with PM2 in NodeJS. Without PM2, we always have some lines of code, as shown below, for setting up the master process.

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

Exactly, I want to send a message from the worker to the master, then the master will send a message to all the employees to notify of the event.

Actually, I saw that when using PM2, line rows in the configuration of the master process are not executed.

Thanks so much for any idea about this issue!

+5
source share
2 answers

With PM2, you usually do not need to use this design. This usually looks like this:

 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 equivalent for above:

 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 more on the topic here

Refresh . You can try to distinguish between master and slave by passing command line arguments. Example example.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 { // ... } 
+6
source

PM2 internally uses the "cluster" to create child processes, and itself performs the role of the leader and does not provide any function for the external one. You can use the following code to create the process, but cluster.isMaster has always been false.

 if(cluster.isMaster){ ... cluster.fork(); ... } else { ... } 

If you don't start like this: pm2 start -x app.js https://github.com/Unitech/pm2/issues/363

The design of the PM2 is good, but it is confused for beginners. We do our best to view documents and google searches, but it’s hard to find any explanation for the design.

0
source

Source: https://habr.com/ru/post/1239107/


All Articles