0

I'm using pm2 to reload my app but in my test the active requests are cancelled by the reload.

I tested by making an endpoint with an await of 10 seconds, requesting a response to this endpoint with Insomnia and then, before the 10 seconds await completes, reloading the app with pm2 reload . But what happens is that the pm2 reload stops the Insomnia request, which finishes as "Error: Server returned nothing (no headers, no data)".

Am I doing something wrong? Was not pm2 supposed to identify current running requests on await state? It could be a real production request where the app was waiting for a database response.

Márcio Valim
  • 2,459
  • 3
  • 10
  • 21

1 Answers1

1

You can catch the SIGTERM signal from within your node.js/express application:

process.on('SIGTERM', () => {
  console.info('SIGTERM signal received.');
  console.log('Close http server.');
  server.close(() => {
    console.log('Http server closed.');
    // You can close here other things that needs to, for example a mongodb/mongoose connection
    mongoose.connection.close(false, () => {
      console.log('MongoDb connection closed.');
      process.exit(0);
    });
  });
});
Alaindeseine
  • 3,260
  • 1
  • 11
  • 21
  • But how closing my database will help my current active requests being answered? – Márcio Valim Sep 09 '22 at 15:21
  • HTTP closing is handle by `server.close(() => {`. Scheme is 1 - intercept SIGTERM signal 2 - Close gracefully http server 3 - Close database connections (Mongo, Mysql, etc.) This code assume your http server is called `server`` – Alaindeseine Sep 09 '22 at 19:02
  • Thanks! I added increasing kill timeout to your solution and my problem was solved. pm2 increase kill timeout: https://pm2.keymetrics.io/docs/usage/signals-clean-restart/ – Márcio Valim Sep 10 '22 at 02:57