Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging/namespacing PM2 apps

Tags:

node.js

pm2

There is PM2 configuration, /home/foo/someconfig.json

{
    "apps": [
        {
            "name": "foo-main",
            "script": "./index.js",
        },
        {
            "name": "foo-bar",
            "script": "./bar.js"
        },
        {
            "name": "foo-baz",
            "script": "./baz.js"
        }
    ]
}

Most of the time I want to refer to all of the apps under current namespace, e.g.

pm2 restart foo

instead of doing

pm2 restart foo-main foo-bar foo-baz

Bash brace extension cannot be used because apps may run in Windows.

Doing pm2 restart /home/foo/someconfig.json isn't a good option, because it takes some time to figure out config file path, it may differ between projects and even change its location.

Can foo-* apps be merged into single foo app or be referred altogether in another reasonable way?

like image 517
Estus Flask Avatar asked Mar 27 '17 00:03

Estus Flask


2 Answers

pm2 supports regex's since 2.4.0, e.g.

pm2 restart /^foo-/

If using with the start command, remember to provide the eco system file as first parameter.

like image 144
mrtnlrsn Avatar answered Sep 20 '22 20:09

mrtnlrsn


It seems that pm2 itself doesn't support wildcard-based restart, but it is not complex to make a simple script to do it using pm2 programmatic API.

Here is a working script that demonstrates the idea:

var pm2 = require('pm2');

pm2.connect(function(err) {
  if (err) {
    console.error(err);
    process.exit(2);
  }

  pm2.list(function(err, processDescriptionList) {
    if (err) throw err;
    for (var idx in processDescriptionList) {
      var name = processDescriptionList[idx]['name'];
      console.log(name);
      if (name.startsWith('foo')) {
        pm2.restart(name, function(err, proc) {
          if (err) throw err;
          console.log('Restarted: ');
          console.log(proc);
        });
      }
    }
  });
});

To make it fully functional, it is also necessary to pass foo as command-line argument (now it is hard-coded) and handle exit (now it works, but doesn't exit on finish).

Here is the full code example, including small sample apps and config.

like image 44
Boris Serebrov Avatar answered Sep 19 '22 20:09

Boris Serebrov