Deployment and Production
6 min read
🚀 Deployment and Production in NestJS
Welcome back! So you've built your awesome NestJS application. Now it's time to release it into the wild. This guide will walk you through the essential steps to get your app ready for production, making it fast, reliable, and easy to manage.
💨 Performance Optimization: Switching to Fastify
The Problem: By default, NestJS uses the Express.js framework. Express is fantastic and widely used, but when it comes to raw speed, there's a faster kid on the block: Fastify. For applications that need to handle a high volume of requests with low overhead, squeezing out every bit of performance is crucial.
The Solution: NestJS is built to be platform-agnostic, meaning you can easily swap out its underlying HTTP framework. Fastify is a popular choice for performance-critical applications. Benchmarks have shown that Fastify can handle significantly more requests per second than Express.
How it Works: NestJS achieves this flexibility through an adapter that proxies middleware and handlers to the specific framework's implementation.
Getting Started with Fastify
1. Installation:
First, you'll need to install the necessary package:
npm install --save @nestjs/platform-fastify2. Switching the Adapter:
Next, you'll modify your main.ts file to use the FastifyAdapter.
// main.ts
import { NestFactory } from '@nestjs/core';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(),
);
await app.listen(3000);
}
bootstrap();And just like that, you've supercharged your NestJS application!
A word of caution: While Fastify is a great choice for many applications, keep in mind that some Express-specific middleware may not be compatible. You'll need to find Fastify-equivalent packages.
📦 Containerizing Your NestJS App with Docker
The Problem: Imagine you've developed your application on your machine, and it works perfectly. But when you deploy it to a server, it breaks because of differences in the environment (like Node.js version, operating system, etc.). This is a classic "it works on my machine" problem.
The Solution: Docker solves this by packaging your application and its dependencies into a standardized unit called a container. This container can run on any machine that has Docker installed, ensuring consistency across different environments.
Creating a Dockerfile
A Dockerfile is a text file that contains the instructions for building a Docker image. Here's a production-ready Dockerfile for a NestJS application using a multi-stage build to keep the final image small and secure.
# Stage 1: Build the application
FROM node:20-alpine AS build
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Prune development dependencies
RUN npm prune --production
# Stage 2: Create the production image
FROM node:20-alpine
WORKDIR /usr/src/app
COPY --from=build /usr/src/app/node_modules ./node_modules
COPY --from=build /usr/src/app/dist ./dist
# The command to run the application
CMD ["node", "dist/main"]What's happening here?
- Multi-stage build: We use two separate stages. The
buildstage installs all dependencies (includingdevDependencies) to build the application. The final, much smaller, production stage only copies over the built application and its production dependencies. node:20-alpine: We use a lightweight Alpine Linux-based Node.js image to keep the final container size down.npm ci: This command is generally faster and more reliable for installing dependencies in a continuous integration/build environment.
Don't forget to create a .dockerignore file in your project's root to exclude unnecessary files from your Docker image, which helps in reducing the build context and image size.
node_modules
dist
.git
.env🏭 Building and Bootstrapping for Production Environments
The Problem: The way you run your application in development is often different from how it should run in production. In production, you need a compiled, optimized version of your code.
The Solution: NestJS provides a straightforward build process that compiles your TypeScript code into JavaScript. The resulting dist folder contains everything you need to run your application in a production environment.
The Build Process
To create a production build, simply run:
npm run buildThis command executes the nest build script, which compiles your TypeScript and copies any non-TypeScript files (like .graphql files) to the dist directory.
Production main.ts
Your main.ts file is the entry point of your application. For production, you might want to add a few things, like enabling CORS or graceful shutdown hooks.
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Enable CORS for all origins
app.enableCors();
// Enable shutdown hooks
app.enableShutdownHooks();
await app.listen(process.env.PORT || 3000);
}
bootstrap();What's new?
app.enableCors(): This enables Cross-Origin Resource Sharing, which is often necessary when your frontend and backend are hosted on different domains.app.enableShutdownHooks(): This ensures that your application gracefully shuts down, closing any open connections before the process exits. This is particularly important for health checks with Terminus.
❤️ Application Health Checks with Terminus
The Problem: Once your application is deployed, how do you know if it's running correctly? A simple "is it running?" check isn't enough. What if its database connection is down, or it's running out of memory?
The Solution: Health checks provide a way to monitor the status of your application and its dependencies. NestJS has a great module called @nestjs/terminus that makes implementing health checks easy.
Setting up Terminus
1. Installation:
npm install --save @nestjs/terminus2. Creating a Health Module:
It's a good practice to organize your health check logic in a dedicated module.
nest g module health
nest g controller health --no-spec3. Implementing the Health Check Endpoint:
Now, let's set up a health check endpoint in our health.controller.ts.
// health.controller.ts
import { Controller, Get } from '@nestjs/common';
import { HealthCheckService, HttpHealthIndicator, HealthCheck } from '@nestjs/terminus';
@Controller('health')
export class HealthController {
constructor(
private health: HealthCheckService,
private http: HttpHealthIndicator,
) {}
@Get()
@HealthCheck()
check() {
return this.health.check([
() => this.http.pingCheck('nestjs-docs', 'https://docs.nestjs.com'),
]);
}
}And in your health.module.ts:
// health.module.ts
import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
import { HttpModule } from '@nestjs/axios';
import { HealthController } from './health.controller';
@Module({
imports: [TerminusModule, HttpModule],
controllers: [HealthController],
})
export class HealthModule {}Now, if you visit /health, Terminus will check if it can successfully ping the NestJS documentation. If it can, it will return a 200 OK response with the status of your health indicators.
Pre-defined Health Indicators
@nestjs/terminus comes with several built-in indicators for common services:
HttpHealthIndicatorTypeOrmHealthIndicatorMongooseHealthIndicatorMemoryHealthIndicatorDiskHealthIndicator
You can also create your own custom health indicators to check the status of any service your application depends on.
📚 References for Extra Reading
- NestJS Documentation:
- Docker Documentation: Get Started
- Fastify Website: fastify.io
Challenge
You are tasked with preparing a NestJS application for a production deployment. Your goal is to refactor the application's entry point (main.ts) for performance and reliability, and to add a comprehensive health check endpoint.
Requirements
In main.ts:
- Switch the underlying HTTP server from the default Express platform to Fastify for improved performance.
- Configure the application to be production-ready by enabling CORS for all origins and enabling graceful shutdown hooks.
- Modify the application to listen on the port specified in the
PORTenvironment variable. If thePORTvariable is not set, it should default to3000.
In health.controller.ts:
- Create a new controller,
HealthController, that will handle requests to the/healthroute. - Implement a GET endpoint at the root of this controller that performs a health check using the
@nestjs/terminusmodule. - The health check must verify two conditions:
- The application's heap memory usage is not exceeding 150MB. Use
'memory_heap'as the key for this check. - An external service at
https://docs.nestjs.comis reachable. Use'nestjs_docs'as the key for this check.
- The application's heap memory usage is not exceeding 150MB. Use
Expected result
Your final code should consist of two parts: the modified main.ts and the new health.controller.ts.
main.ts
- It must import
FastifyAdapterfrom@nestjs/platform-fastify. - The
NestFactory.createmethod must be called with a new instance ofFastifyAdapteras its second argument. - The
appinstance must callenableCors()andenableShutdownHooks(). - The
app.listen()method must useprocess.env.PORTas the primary port, with3000as a fallback.
health.controller.ts
- A class named
HealthControllermust be defined and decorated with@Controller('health'). - The constructor of
HealthControllermust injectHealthCheckService,HttpHealthIndicator, andMemoryHealthIndicator. - It must contain one method, decorated with
@Get()and@HealthCheck(). - This method should call
this.health.check()with an array containing the results of two checks:this.memory.checkHeap('memory_heap', 150 * 1024 * 1024)this.http.pingCheck('nestjs_docs', 'https://docs.nestjs.com')