Search code examples
node.jspm2spawn

Reload all pm2 clusters from within 1 of the clusters


I have a nodejs application running on multiple pm2 clusters. I created a route through which I update the code for the application (pull new code from Git remote) and then I attempt to reload all pm2 clusters by using exec to run reload command (pm2 reload [server]).

The problem I encountered is, once the cluster that that initiated the process terminates in order to reload, it won't continue reloading the remaining clusters.

So, after researching (Reading node documentation and looking at this SO question) it seemed obvious that the correct way to handle this, is to spawn a child process and run the unref() method on it. This, however, didn't change anything. Some clusters reload but not all.

Here's the code:

const {spawn} = require('child_process');
const reload = spawn(`pm2`, [`reload`, `server`], {detached: true, stdio: 'ignore'});
reload.unref();

I also tried adding reload.disconnect(), based on the node , but got an error disconnect is not a function.

In addition, instead of running the command 'pm2 reload server' in the child process, I tried executing a bash file, that contained the command, through the detached child process. The results were the same.

In summary I want to know how to have the reloads for all clusters continue even after the cluster that initiated the process terminates. I would also like to know, why the ways I have tried did not work.


Solution

  • I still don't know why it wasn't working the way I posted in the question.

    However, what did work for me is running a js file with the detached spawned child process, that in turn runs a detached spawned child process that executes the reload command.

    In the first file I have:

    const {spawn} = require('child_process');
    const reload = spawn(`node`, [`/reload.js`], {detached: true, stdio: 'ignore'});
    reload.unref();
    

    and in reload.js I have:

    const {spawn} = require('child_process');
    const reload = spawn(`pm2`, [`reload`, `server`], {detached: true, stdio: 'ignore'});
    reload.unref();
    

    Note: I first tried using exec in reload.js and that got the same results outlined in the question.

    I hope this helps anyone trying to accomplish anything similar.