Node.js getting SIGINT from pm2
08:56 30 May 2018

I'm trying to use pm2 to run my node app as a service.

Right now, starting and stopping the app works. However, I want to do a graceful shutdown.

My app already listens for SIGINT, shutdowns the server and then exits the process. However, trying to put pm2 to send the SIGINT, just causes the app to restart, like if pm2 was killing and starting it again.

This is how I create the process:

pm2 start server.js --name ProcessName --silent --kill-timeout 3000

Here's my app's code for listening the SIGINT:

process.on("SIGINT", function () {
    //graceful shutdown
    server.end().then(() => {
        process.exit();
    }).catch((err) => {
        console.error(err);
    });

});

Then to shutdown the app using pm2, I'm running:

pm2 sendSignal SIGINT ProcessName

Which, again, restarts the app.

Reading over pm2 docs, I found that pm2 will also send a shutdown event to the app, so I added:

process.on('message', function(msg) {
    if (msg == 'shutdown') {
        server.end().then(() => {
            process.exit();
        }).catch((err) => {
            console.error(err);
        });
    }
});

Which isn't working either.

Any idea how to solve this?

Thanks!

node.js pm2