Merging/namespacing PM2 apps
Asked Answered
P

2

12

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?

Predestination answered 27/3, 2017 at 0:0 Comment(0)
T
5

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.

Thaw answered 25/6, 2021 at 9:12 Comment(1)
Thanks, I was searching for the term 'pm2 application wildcard' found no success, thought this might help future googlers.Batt
U
6

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.

Underlet answered 25/5, 2017 at 19:8 Comment(1)
Thanks, that's a good use of pm2 API. I wish there was a conventional way to do this, since global pm2 command with no extra hassle has its benefits.Predestination
T
5

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.

Thaw answered 25/6, 2021 at 9:12 Comment(1)
Thanks, I was searching for the term 'pm2 application wildcard' found no success, thought this might help future googlers.Batt

© 2022 - 2024 — McMap. All rights reserved.