### Dockerfile for NestJS with Graceful Shutdown Source: https://context7.com/tygra-io/nestjs-graceful-shutdown/llms.txt This Dockerfile defines the build process for a NestJS application designed for graceful shutdown. It installs production dependencies, copies application code, builds the application, and exposes the necessary port. The `CMD` instruction ensures the application starts correctly, with graceful shutdown handled by the Node.js process receiving SIGTERM. ```dockerfile FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm ci --only=production COPY . . RUN npm run build EXPOSE 3000 # Graceful shutdown handles SIGTERM from Docker CMD ["node", "dist/main.js"] ``` -------------------------------- ### Setup graceful shutdown for NestJS application Source: https://github.com/tygra-io/nestjs-graceful-shutdown/blob/main/README.md Initializes graceful shutdown handling for the NestJS application by calling setupGracefulShutdown with the application instance. Automatically enables shutdown hooks and handles SIGTERM signals. Avoid using enableShutdownHooks separately to prevent conflicts. ```typescript import { setupGracefulShutdown } from '@tygra/nestjs-graceful-shutdown'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); // Additional configuration for your NestJS app setupGracefulShutdown({ app }); await app.listen(3000); // Note: Timeout is used for illustration of // delayed termination purposes only. setTimeout(() => { process.kill(process.pid, 'SIGTERM'); }, 5000); } bootstrap(); ``` -------------------------------- ### Fastify Application with Graceful Shutdown (TypeScript) Source: https://context7.com/tygra-io/nestjs-graceful-shutdown/llms.txt This example shows a complete NestJS application using the Fastify adapter that seamlessly integrates graceful shutdown. It demonstrates how to configure the shutdown timeout and a cleanup function that executes before the application exits. The application includes a simple API endpoint for streaming data. ```typescript import { Module, Controller, Get } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'; import { GracefulShutdownModule, setupGracefulShutdown } from '@tygra/nestjs-graceful-shutdown'; @Controller('api') class ApiController { @Get('stream') async streamData(): Promise<{ chunks: number[]; total: number }> { const chunks: number[] = []; // Simulate streaming data for (let i = 0; i < 10; i++) { await new Promise(resolve => setTimeout(resolve, 500)); chunks.push(i); } return { chunks, total: chunks.length }; } } @Module({ imports: [ GracefulShutdownModule.forRoot({ gracefulShutdownTimeout: 10000, cleanup: async (app, signal) => { console.log(`Fastify app shutting down: ${signal}`); }, }), ], controllers: [ApiController], }) class FastifyAppModule {} async function bootstrap() { const app = await NestFactory.create( FastifyAppModule, new FastifyAdapter({ logger: true }) ); setupGracefulShutdown({ app }); await app.listen(3000, '0.0.0.0'); console.log('Fastify server running on http://localhost:3000'); } bootstrap(); ``` -------------------------------- ### Initialize graceful shutdown in bootstrap (NestJS Graceful Shutdown) Source: https://context7.com/tygra-io/nestjs-graceful-shutdown/llms.txt Calls setupGracefulShutdown in the bootstrap function to attach SIGTERM/SIGINT handlers and initialize the HTTP terminator. Place it after CORS/global prefix setup but before app.listen. ```TypeScript import { NestFactory } from '@nestjs/core'; import { setupGracefulShutdown } from '@tygra/nestjs-graceful-shutdown'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule, { logger: ['error', 'warn', 'log'], }); app.enableCors({ origin: process.env.ALLOWED_ORIGINS?.split(',') || '*', }); app.setGlobalPrefix('api/v1'); setupGracefulShutdown({ app }); const port = process.env.PORT || 3000; await app.listen(port); console.log(`Application is running on: http://localhost:${port}`); } bootstrap().catch((err) => { console.error('Failed to start application:', err); process.exit(1); }); ``` -------------------------------- ### Complete Express Application with Graceful Shutdown Source: https://context7.com/tygra-io/nestjs-graceful-shutdown/llms.txt This example showcases a full NestJS application using the Express adapter, integrating graceful shutdown. It includes a `DatabaseService` for managing connections and a `TasksController` with a long-running endpoint. The `GracefulShutdownModule` is configured with a timeout and a cleanup function to disconnect the database. ```typescript import { Module, Controller, Get, Injectable } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { GracefulShutdownModule, setupGracefulShutdown } from '@tygra/nestjs-graceful-shutdown'; // Service with database connection @Injectable() class DatabaseService { private connected = false; async connect() { console.log('Connecting to database...'); this.connected = true; } async disconnect() { console.log('Disconnecting from database...'); this.connected = false; } isConnected() { return this.connected; } } // Controller with long-running endpoint @Controller('tasks') class TasksController { constructor(private db: DatabaseService) {} @Get('long-running') async longRunningTask(): Promise<{ status: string; duration: number }> { const start = Date.now(); // Simulate long-running operation await new Promise(resolve => setTimeout(resolve, 8000)); return { status: 'completed', duration: Date.now() - start, }; } @Get('health') healthCheck() { return { status: 'healthy', database: this.db.isConnected(), timestamp: new Date().toISOString(), }; } } @Module({ imports: [ GracefulShutdownModule.forRoot({ gracefulShutdownTimeout: 15000, // Wait up to 15 seconds for requests cleanup: async (app) => { const db = app.get(DatabaseService); await db.disconnect(); }, }), ], controllers: [TasksController], providers: [DatabaseService], }) class AppModule {} async function bootstrap() { const app = await NestFactory.create(AppModule); // Initialize database const db = app.get(DatabaseService); await db.connect(); // Setup graceful shutdown setupGracefulShutdown({ app }); await app.listen(3000); console.log('Server running on http://localhost:3000'); console.log('Try: curl http://localhost:3000/tasks/long-running'); console.log('Then send SIGTERM to test graceful shutdown'); } bootstrap(); ``` -------------------------------- ### Testing Graceful Shutdown without Mock Module using app.listen() Source: https://github.com/tygra-io/nestjs-graceful-shutdown/blob/main/README.md This example demonstrates an alternative testing strategy for graceful shutdown in NestJS applications where a mock module is not used. Instead, it utilizes `app.listen()` within a `beforeEach` hook after setting up the graceful shutdown, bypassing the need for explicit module overriding. This approach is suitable when direct application initialization and listening are preferred. ```typescript beforeEach(async () => { const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule], }).compile(); app = moduleFixture.createNestApplication(); setupGracefulShutdown({ app }); await app.listen(); }); ``` -------------------------------- ### Testing NestJS with Mocked Graceful Shutdown (TypeScript) Source: https://context7.com/tygra-io/nestjs-graceful-shutdown/llms.txt This example illustrates how to test a NestJS application while mocking the graceful shutdown module. By overriding `GracefulShutdownModule` with a mock module, actual shutdown behavior is prevented during tests, ensuring test isolation and reliability. This is crucial for maintaining a stable testing environment. ```typescript import { Test, TestingModule } from '@nestjs/testing'; import { INestApplication, Module } from '@nestjs/common'; import { GracefulShutdownModule } from '@tygra/nestjs-graceful-shutdown'; import { AppModule } from '../src/app.module'; // Mock module for testing @Module({}) class MockGracefulShutdownModule {} describe('AppController (e2e)', () => { let app: INestApplication; beforeEach(async () => { const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule], }) .overrideModule(GracefulShutdownModule) .useModule(MockGracefulShutdownModule) .compile(); app = moduleFixture.createNestApplication(); await app.init(); }); afterEach(async () => { await app.close(); }); it('should handle requests normally', async () => { // Your test assertions expect(app).toBeDefined(); }); }); ``` -------------------------------- ### Production-Ready NestJS Bootstrap for Docker (TypeScript) Source: https://context7.com/tygra-io/nestjs-graceful-shutdown/llms.txt This TypeScript code demonstrates a production-ready bootstrap process for a NestJS application within a Docker environment. It configures application logging based on the `NODE_ENV` and sets up graceful shutdown using the `setupGracefulShutdown` function. This ensures the application responds correctly to termination signals from container orchestrators like Docker. ```typescript import { NestFactory } from '@nestjs/core'; import { setupGracefulShutdown } from '@tygra/nestjs-graceful-shutdown'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule, { logger: process.env.NODE_ENV === 'production' ? ['error', 'warn'] : ['error', 'warn', 'log', 'debug'], }); // Setup graceful shutdown for Docker/Kubernetes setupGracefulShutdown({ app }); await app.listen(3000, '0.0.0.0'); console.log(`Application started in ${process.env.NODE_ENV} mode`); console.log(`Graceful shutdown timeout: ${process.env.GRACEFUL_SHUTDOWN_TIMEOUT}ms`); } bootstrap(); ``` -------------------------------- ### Configure GracefulShutdownModule asynchronously with dependencies Source: https://github.com/tygra-io/nestjs-graceful-shutdown/blob/main/README.md Asynchronously configures GracefulShutdownModule by injecting services like ConfigService. Uses forRootAsync method with imports, inject, and useFactory properties. Enables dynamic configuration based on external services or environment variables. ```typescript import { GracefulShutdownModule } from '@tygra/nestjs-graceful-shutdown'; @Injectable() class ConfigService { public readonly timeout = 10000; } @Module({ providers: [ConfigService], exports: [ConfigService] }) class ConfigModule {} @Module({ imports: [ GracefulShutdownModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: async (config: ConfigService) => { await somePromise(); return { gracefulShutdownTimeout: config.timeout, }; } }) ], ... }) class AppModule {} ``` -------------------------------- ### Define graceful shutdown configuration interfaces Source: https://github.com/tygra-io/nestjs-graceful-shutdown/blob/main/README.md Defines the configuration interfaces used for GracefulShutdownModule and setupGracefulShutdown function. Includes options for cleanup functions and timeout settings. These interfaces help structure configuration objects for graceful shutdown behavior. ```typescript interface IGracefulShutdownConfigOptions { /** * Cleanup function for releasing application resources * during server shutdown. */ cleanup?: (app: INestApplication, signal?: string) => any; /** * The duration in milliseconds before forcefully * terminating a connection. * Defaults: 5000 (5 seconds). */ gracefulShutdownTimeout?: number; } ``` ```typescript interface ISetupFunctionParams { /** * Your NestJS application. */ app: INestApplication; /** * Shutdown signals that the application should listen to. * By default, it listens to all ShutdownSignals. */ signals?: ShutdownSignal[] | string[]; } ``` -------------------------------- ### Kubernetes Deployment Configuration for NestJS Graceful Shutdown Source: https://context7.com/tygra-io/nestjs-graceful-shutdown/llms.txt Complete Kubernetes deployment manifest for NestJS application with graceful shutdown configuration. Includes environment variables for shutdown timeout, health checks, resource limits, and lifecycle preStop hook to ensure proper termination sequence. Configures rolling update strategy and service definition for load balancer integration. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: nestjs-app labels: app: nestjs-app spec: replicas: 3 strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 maxUnavailable: 0 selector: matchLabels: app: nestjs-app template: metadata: labels: app: nestjs-app spec: containers: - name: api image: your-registry/nestjs-app:latest ports: - containerPort: 3000 env: - name: GRACEFUL_SHUTDOWN_TIMEOUT value: "30000" - name: NODE_ENV value: "production" livenessProbe: httpGet: path: /health port: 3000 initialDelaySeconds: 30 periodSeconds: 10 readinessProbe: httpGet: path: /health port: 3000 initialDelaySeconds: 5 periodSeconds: 5 lifecycle: preStop: exec: # Kubernetes sends SIGTERM after this completes # Add small delay to ensure load balancer stops routing command: ["/bin/sh", "-c", "sleep 5"] resources: requests: memory: "256Mi" cpu: "250m" limits: memory: "512Mi" cpu: "500m" # Allow graceful shutdown to complete (must be > GRACEFUL_SHUTDOWN_TIMEOUT) terminationGracePeriodSeconds: 40 --- apiVersion: v1 kind: Service metadata: name: nestjs-app-service spec: selector: app: nestjs-app ports: - protocol: TCP port: 80 targetPort: 3000 type: LoadBalancer ``` -------------------------------- ### Configure GracefulShutdownModule with synchronous options Source: https://github.com/tygra-io/nestjs-graceful-shutdown/blob/main/README.md Configures the GracefulShutdownModule with synchronous configuration options including cleanup function and timeout settings. Accepts an object matching IGracefulShutdownConfigOptions interface. Useful when configuration values are known at compile time. ```typescript import { GracefulShutdownModule } from '@tygra/nestjs-graceful-shutdown'; @Module({ imports: [ GracefulShutdownModule.forRoot({ cleanup: async (app, signal) => { // releasing resources }, gracefulShutdownTimeout: Number(process.env.GRACEFUL_SHUTDOWN_TIMEOUT ?? 10000), }) ], ... }) class AppModule {} ``` -------------------------------- ### Docker Compose for Graceful Shutdown (YAML) Source: https://context7.com/tygra-io/nestjs-graceful-shutdown/llms.txt This docker-compose configuration sets up a multi-container application with an API service and a database. It highlights the `stop_grace_period` for the API service, allowing time for graceful shutdown signals to be processed. Environment variables are used to configure the shutdown timeout and database connection. ```yaml version: '3.8' services: api: build: . ports: - "3000:3000" environment: - NODE_ENV=production - GRACEFUL_SHUTDOWN_TIMEOUT=30000 - DATABASE_URL=postgresql://postgres:password@db:5432/myapp depends_on: - db # Docker sends SIGTERM on stop stop_grace_period: 35s healthcheck: test: ["CMD", "curl", "-f", "http://localhost:3000/health"] interval: 10s timeout: 5s retries: 3 db: image: postgres:14 environment: - POSTGRES_PASSWORD=password - POSTGRES_DB=myapp ``` -------------------------------- ### Register module with synchronous config (NestJS Graceful Shutdown) Source: https://context7.com/tygra-io/nestjs-graceful-shutdown/llms.txt Registers GracefulShutdownModule with a static configuration, including a cleanup function and timeout. Dependencies like DatabaseService and QueueService should be provided in the module. Cleanup runs on shutdown signals or app.close(). ```TypeScript import { Module } from '@nestjs/common'; import { GracefulShutdownModule } from '@tygra/nestjs-graceful-shutdown'; @Module({ imports: [ GracefulShutdownModule.forRoot({ gracefulShutdownTimeout: 10000, cleanup: async (app, signal) => { const dbService = app.get(DatabaseService); await dbService.disconnect(); const queueService = app.get(QueueService); await queueService.close(); console.log(`Cleanup completed for signal: ${signal}`); }, }), ], controllers: [AppController], providers: [AppService, DatabaseService, QueueService], }) export class AppModule {} ``` -------------------------------- ### Import GracefulShutdownModule in AppModule Source: https://github.com/tygra-io/nestjs-graceful-shutdown/blob/main/README.md Imports the GracefulShutdownModule into the root AppModule using forRoot(). This enables graceful shutdown capabilities in the NestJS application. No additional configuration is required for basic usage. ```typescript import { GracefulShutdownModule } from '@tygra/nestjs-graceful-shutdown'; @Module({ imports: [GracefulShutdownModule.forRoot()], ... }) class AppModule {} ``` -------------------------------- ### Mocking Graceful Shutdown Module with overrideModule Source: https://github.com/tygra-io/nestjs-graceful-shutdown/blob/main/README.md This code snippet shows how to replace the `GracefulShutdownModule` with a `MockModule` during testing using NestJS's `overrideModule` and `useModule` methods. This is useful for isolating the module under test. It requires the `TestingModule` and `Test.createTestingModule` from NestJS. ```typescript const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule], }) .overrideModule(GracefulShutdownModule) .useModule(MockModule) .compile(); ``` -------------------------------- ### Configure Custom Shutdown Signals in NestJS Source: https://context7.com/tygra-io/nestjs-graceful-shutdown/llms.txt This snippet demonstrates how to configure the graceful shutdown to listen to specific signals (SIGTERM and SIGINT) instead of the default ones. This allows for more control over when and how the application initiates its shutdown sequence, which can be useful in different deployment environments. ```typescript import { NestFactory, ShutdownSignal } from '@nestjs/core'; import { setupGracefulShutdown } from '@tygra/nestjs-graceful-shutdown'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); // Only listen to specific signals setupGracefulShutdown({ app, signals: [ShutdownSignal.SIGTERM, ShutdownSignal.SIGINT], }); await app.listen(3000); // Simulate a shutdown after 10 seconds (for testing) if (process.env.NODE_ENV === 'development') { setTimeout(() => { console.log('Triggering graceful shutdown...'); process.kill(process.pid, 'SIGTERM'); }, 10000); } } bootstrap(); ``` -------------------------------- ### Register module with async config via DI (NestJS Graceful Shutdown) Source: https://context7.com/tygra-io/nestjs-graceful-shutdown/llms.txt Registers GracefulShutdownModule asynchronously by injecting ConfigService (or other providers) into a useFactory. Useful for reading environment variables at startup or performing async validation before returning the configuration. ```TypeScript import { Module, Injectable } from '@nestjs/common'; import { GracefulShutdownModule } from '@tygra/nestjs-graceful-shutdown'; @Injectable() class ConfigService { getShutdownTimeout(): number { return parseInt(process.env.GRACEFUL_SHUTDOWN_TIMEOUT || '5000', 10); } getDatabaseUrl(): string { return process.env.DATABASE_URL || 'postgresql://localhost:5432/db'; } } @Module({ providers: [ConfigService], exports: [ConfigService], }) class ConfigModule {} @Module({ imports: [ GracefulShutdownModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: async (configService: ConfigService) => { await validateConfiguration(); return { gracefulShutdownTimeout: configService.getShutdownTimeout(), cleanup: async (app, signal) => { const logger = app.get(Logger); logger.log(`Shutting down due to ${signal}`); const connectionPool = app.get(ConnectionPool); await connectionPool.drain(); }, }; }, }), ], }) export class AppModule {} ``` -------------------------------- ### IGracefulShutdownConfigOptions Interface Definition Source: https://context7.com/tygra-io/nestjs-graceful-shutdown/llms.txt This code defines the IGracefulShutdownConfigOptions interface, providing TypeScript type safety for configuring graceful shutdown. It includes properties for `gracefulShutdownTimeout` to set a duration for pending operations and an optional `cleanup` async function for custom resource deallocation before the application exits. ```typescript import { INestApplication } from '@nestjs/common'; import { IGracefulShutdownConfigOptions } from '@tygra/nestjs-graceful-shutdown'; // Example configuration object const config: IGracefulShutdownConfigOptions = { // Timeout in milliseconds before forcefully closing connections gracefulShutdownTimeout: 30000, // 30 seconds for long-running requests // Optional cleanup function called during shutdown cleanup: async (app: INestApplication, signal?: string) => { console.log(`Starting cleanup for signal: ${signal}`); try { // Close WebSocket connections const wsGateway = app.get(WebSocketGateway); await wsGateway.closeAllConnections(); // Flush metrics before shutdown const metricsService = app.get(MetricsService); await metricsService.flush(); // Close Redis connections const redis = app.get(RedisService); await redis.disconnect(); console.log('Cleanup completed successfully'); } catch (error) { console.error('Error during cleanup:', error); // Error is logged but doesn't prevent shutdown } }, }; export default config; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.