Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nest.js gracefully shutdown [duplicate]

Tags:

node.js

nestjs

I enabled shutdown hooks at my bootstrap function. Also I subscribed on application shutdown hook at one of my modules:

public async onApplicationShutdown(signal): Promise<void>
{
   console.log({signal});
   ...
}

Now I can press Ctrl+C and read an excellent message at terminal. Then my resource release works correctly.

Also I want to close my app if db connection failed:

export class MyDbAccessImplementation {
   constructor() {
      this._pool = createPool(some);
      this._pool.query(`SELECT 'test' AS TEST`, (err) => {
         if (err !== null) {
            console.error(err);
            process.emit('SIGINT');
         }
      });
   }
}

But in this case my onApplicationShutdown method does not triggered on db connection error and the application closes instantly.

How I can trigger Nest.js application shutdown from its component?

like image 543
muturgan Avatar asked Apr 24 '26 07:04

muturgan


1 Answers

I believe your problem might be that your NestJS instance is not listening for shutdown events. You need to enable that behavior with app.enableShutdownHooks() in you bootstrap.

This is from their Lifecycles Events guide:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // Starts listening for shutdown hooks
  app.enableShutdownHooks();

  await app.listen(3000);
}
like image 136
JP de la Torre Avatar answered Apr 25 '26 22:04

JP de la Torre