Nâng CaoNestJS iconNestJS

Health checks và graceful shutdown trong NestJS production?

Health Checks với @nestjs/terminus:

typescript
import { TerminusModule, TypeOrmHealthIndicator, HealthCheckService } from '@nestjs/terminus';
// Lưu ý: HealthController là controller do user tạo, không phải từ @nestjs/terminus.

@Module({ imports: [TerminusModule] })
export class HealthModule {}

// controller
@Get('health')
@HealthCheck()
check() {
  return this.health.check([
    () => this.db.pingCheck('database'),
    () => this.http.pingCheck('redis', 'http://redis:6379'),
    () => this.memory.checkHeap('memory_heap', 300 * 1024 * 1024),
  ]);
}

Graceful Shutdown: đảm bảo app xử lý xong in-flight requests trước khi shutdown:

typescript
// main.ts
app.enableShutdownHooks(); // Listen SIGTERM, SIGINT

// Service có thể implement OnApplicationShutdown
async onApplicationShutdown(signal?: string) {
  this.logger.log(`Shutting down on signal: ${signal}`);
  await this.closeConnections();
}

Kubernetes gửi SIGTERM khi pod bị terminate — NestJS cần hoàn thành requests đang xử lý trước khi exit.

Set terminationGracePeriodSeconds: 30 trong K8s manifest.

Xem toàn bộ NestJS cùng filter theo level & chủ đề con.

Mở danh sách NestJS