Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 42 ยท Testing and Production

Deployment and Performance

Ship a NestJS app: build output, a Docker image, the Fastify adapter, compression, graceful shutdown hooks, Terminus health checks, logging and monorepos.

Development runs TypeScript with a watcher on your laptop. Production runs compiled JavaScript on a server you do not sit next to, restarted by an orchestrator, watched by a load balancer. The gap between the two is where many first deployments hurt: images that are huge, processes that drop requests when they restart, and health checks that say "fine" while the database is down.

This lesson walks the path from nest build to a running container that starts, reports its health, and stops politely. The real commands and Nest code are read-only (they need Node, npm and Docker). The runnable stand-ins are plain Node: a health-check aggregator, and a loopback server that shuts down gracefully, so you can see the behavior these features exist to provide.

From source to running container

Build nest build writes dist/.
Image Multi-stage Docker build.
Run node dist/main with env vars.
Observe Health checks and logs.
1 / 2

What nest build produces

nest build compiles TypeScript with the compiler (or SWC if you configured it) and writes JavaScript to dist/. The entry point is dist/main.js:

Terminal
npm run build          # runs "nest build"
node dist/main         # production: no ts-node, no watcher

Production needs only dist/ and the runtime dependencies. Development tools (the Nest CLI, TypeScript, Jest, type packages) belong in devDependencies and should not ship. Decorators need TypeScript's metadata settings (emitDecoratorMetadata) at compile time, but at run time the output is ordinary JavaScript, with no TypeScript compiler involved.

Set NODE_ENV=production. Libraries such as Express use it to enable caching and skip debug work, and your own configuration code may use it to pick settings. Read the port and every other environment-specific value from the environment (see Configuration and Environment), never from constants in code.

A Docker image

A multi-stage build compiles in a full image and copies only the result into a small one:

DOCKERFILE
# --- build stage ---
FROM node:24-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev

# --- runtime stage ---
FROM node:24-slim
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
COPY package.json ./
USER node
EXPOSE 3000
CMD ["node", "dist/main"]

Why it is shaped this way:

  • Copying package*.json and running npm ci before copying the source lets Docker reuse the dependency layer until the lock file changes.
  • npm prune --omit=dev removes development packages from node_modules after the build.
  • USER node avoids running as root.
  • CMD ["node", "dist/main"] starts Node directly. Wrapping it in npm start adds a process in between that may not forward SIGTERM to your app, which breaks graceful shutdown.
  • A .dockerignore listing node_modules, dist and .git keeps the build context small. More Docker background is in Node.js in Docker and CI.

One more detail: bind the server to 0.0.0.0 inside a container, for example app.listen(port, '0.0.0.0'). Listening only on 127.0.0.1 makes it unreachable from outside the container.

The Fastify adapter

Nest runs on Express by default. Switching to Fastify is a platform choice made when the app is created:

TypeScript
import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';

const app = await NestFactory.create<NestFastifyApplication>(
  AppModule,
  new FastifyAdapter(),
);
await app.listen({ port: 3000, host: '0.0.0.0' });

Fastify generally has lower per-request overhead than Express, but the framework is rarely your bottleneck: database queries, remote calls and serialization usually dominate. Measure before you switch. Remember that Express-specific middleware and @Req()/@Res() code that touches Express types will not work unchanged, so a switch late in a project costs more than a switch on day one. Helmet and compression have Fastify versions (@fastify/helmet, @fastify/compress).

Compression and other cheap wins

Compressing JSON and HTML responses saves bandwidth. In an Express-based app that is one line of middleware:

TypeScript
import compression from 'compression';
app.use(compression());

In larger setups, a reverse proxy or CDN (nginx, a cloud load balancer) compresses and terminates TLS, so the app does not spend CPU on it. Pick one place to compress, not both.

Other changes with a solid payoff:

  • Cache repeated reads and expensive results (Caching, Throttling and Scheduling).
  • Avoid request-scoped providers unless you need them. They create new instances on every request and the cost spreads up the injection chain (Dynamic Modules and Provider Scopes).
  • Paginate list endpoints and select only the columns you return.
  • Use connection pools sized for your database limits, multiplied by the number of app instances.
  • Move slow work to queues (Queues and Events).
  • Scale out with several processes or containers. One Node process uses one core for JavaScript.

Graceful shutdown

When an orchestrator replaces a container it sends SIGTERM, waits a grace period, then SIGKILL. If the app exits at once, requests in flight fail and database work is cut off. Nest ignores shutdown signals by default. You opt in:

TypeScript
const app = await NestFactory.create(AppModule);
app.enableShutdownHooks();       // listen for SIGTERM and SIGINT
await app.listen(3000);

Providers then react through lifecycle hooks:

TypeScript
@Injectable()
export class DatabaseService implements OnModuleDestroy, OnApplicationShutdown {
  async onModuleDestroy() { /* stop accepting new work */ }
  async onApplicationShutdown(signal?: string) {
    await this.pool.end();        // release connections
  }
}

The order on shutdown is onModuleDestroy, then beforeApplicationShutdown, then the HTTP server stops listening, then onApplicationShutdown. Keep the total shutdown time below the orchestrator's grace period. Shutdown hooks add listeners and use some memory when several apps start in one process, which matters mostly for tests that create many apps.

Health checks with Terminus

A load balancer and an orchestrator need to know whether to send traffic to an instance. The @nestjs/terminus package builds a health endpoint from indicators:

TypeScript
@Controller('health')
export class HealthController {
  constructor(
    private readonly health: HealthCheckService,
    private readonly db: TypeOrmHealthIndicator,
    private readonly http: HttpHealthIndicator,
  ) {}

  @Get()
  @HealthCheck()
  check() {
    return this.health.check([
      () => this.db.pingCheck('database'),
      () => this.http.pingCheck('payments', 'https://payments.internal/ping'),
    ]);
  }
}

A healthy response has status: "ok" and HTTP 200. If any indicator fails, the status is "error", the HTTP status is 503, and the body lists which indicator failed. The distinction that matters in production:

Probe Question Should it check the database?
Liveness Is the process stuck? No. A database outage must not restart healthy apps.
Readiness Can it serve traffic now? Yes, so traffic waits until dependencies are up.

Keep liveness trivial and make readiness reflect real dependencies. Protect or hide the health route on the public internet if it exposes internal hostnames.

Logging

Nest's built-in Logger prints levels (log, warn, error, debug, verbose) with a context name. You can limit levels at creation (NestFactory.create(AppModule, { logger: ['error', 'warn', 'log'] })) or plug in another logger. In production prefer structured JSON logs written to standard output, so the platform can collect and search them. A popular route is the pino-based nestjs-pino package. Add a request or correlation ID to every line, never log secrets or whole request bodies, and let the platform, not your app, handle log files and rotation.

Monorepo mode

The Nest CLI can hold several applications and shared libraries in one repository (nest generate app admin, nest generate library shared). The projects are listed in nest-cli.json, and each app builds to its own folder under dist/apps. This suits an API plus a worker that share DTOs and database code. Microservice setups are covered in Microservices and Transports. Keep one image per app, built from the same repository.

Stand-in: a health-check aggregator

This is not Terminus. It imitates the shape of the idea: indicators are functions that resolve or throw, they run together, and any failure turns the whole report into a 503.

Node.js Health indicators and a 503 report

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The second report names the failing indicator and returns 503, which tells a load balancer to stop sending traffic until the check passes again. The healthy indicators are still listed, which helps when you read the response by hand.

Stand-in: shutting down without dropping a request

This one uses a real HTTP server on the loopback address. A slow request is in flight when shutdown begins. The shutdown function stops accepting new connections, waits for the running request, then runs cleanup hooks in Nest's order and finally reports what happened.

Node.js Graceful shutdown: drain, then close

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The request that was already running completed normally. A request that arrives after shutdown began is refused at the connection level, which is what lets a load balancer retry it on another instance. The numbered log shows the hook order. In Nest the framework performs this sequence for you once enableShutdownHooks() is on.

A deployment checklist

  • nest build, run node dist/main, NODE_ENV=production.
  • Small multi-stage image, non-root user, direct node as the command.
  • Configuration from the environment, validated at startup.
  • enableShutdownHooks() and hooks that close pools and connections.
  • Separate liveness and readiness endpoints.
  • JSON logs on standard output; no secrets in them.
  • Migrations run as a deliberate release step, not on every instance start (Transactions and Migrations).
  • Measured performance work, not guesses.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should the Dockerfile CMD be ["node", "dist/main"] rather than npm start?

    Signals go to the container's main process. If that is npm, your Nest app may never learn it should shut down. Running node directly avoids the extra process.
  2. 2. What must you call so Nest reacts to SIGTERM with its shutdown hooks?

    Nest does not listen for shutdown signals by default. enableShutdownHooks() registers the listeners that trigger onModuleDestroy and the other hooks.
  3. 3. A database outage should NOT cause an orchestrator to restart healthy app instances. Which probe should therefore avoid checking the database?

    Liveness answers 'is the process stuck?'. Restarting it will not fix a database. Readiness may check dependencies, so traffic is held back until they recover.
  4. 4. What HTTP status does a Terminus health endpoint return when one indicator fails?

    A failing indicator turns the report into status error and the HTTP response into 503 Service Unavailable, which load balancers understand.
  5. 5. Inside a container the app listens on 127.0.0.1 only. What happens?

    Loopback inside a container is private to that container. Bind to 0.0.0.0 so the published port reaches the app.

Summary

  • nest build writes JavaScript to dist/; production runs node dist/main with NODE_ENV=production and configuration from the environment.
  • Use a multi-stage Docker build, a non-root user and a direct node command; bind to 0.0.0.0.
  • Fastify can lower overhead, but measure first, because queries and remote calls usually dominate; compress in one place only.
  • Call enableShutdownHooks() and close pools in onApplicationShutdown; the order is onModuleDestroy, beforeApplicationShutdown, server close, onApplicationShutdown.
  • Terminus builds health endpoints from indicators and answers 503 on failure; keep liveness simple and make readiness check dependencies.
  • Log JSON to standard output; a monorepo can hold an API and workers that share libraries.

Put everything together in Project: Todo REST API.