Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload Node.JS app without losing current open requests?

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.

like image 458
Márcio Valim Avatar asked Jun 07 '26 20:06

Márcio Valim


1 Answers

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);
    });
  });
});
like image 187
Alaindeseine Avatar answered Jun 10 '26 11:06

Alaindeseine