A NestJS service that runs cleanly with nest start --watch in development can still fall over in production: dev-only modules left in the build, no graceful shutdown, missing reverse proxy, request logging at debug level filling disk. This walks through the actual production deployment — compiling to JS, configuring Nest for production, supervising the process, and the operational details that separate a service that runs from one that survives.
How to verify
Confirm the production build is what is actually running:
node --version # match the engines field in package.json
ls -lh dist/main.js # compiled entrypoint should exist
node -e "console.log(require('./dist/main.js'))" 2>&1 | head -5
systemctl status myapp.service
curl -s http://127.0.0.1:3000/health
journalctl -u myapp --since "5 minutes ago" | tail -20
If dist/main.js is missing, the build step did not run. If systemctl status shows the service crashing in a loop, the configuration is wrong — read the journal first before changing code.
What’s happening
NestJS compiles TypeScript to JavaScript via nest build (which wraps tsc or swc depending on configuration). The output goes to dist/ and is what production actually runs — never ts-node or the watch-mode CLI in production. The build inlines decorators, applies the tsconfig.json paths, and produces a tree that maps 1:1 to your source modules.
In production you also want: NODE_ENV=production (which Nest uses to skip dev-only middleware), a logger configured for JSON output (not the colorized dev logger), a graceful shutdown hook that closes the HTTP server and database connections before exit, and a reverse proxy in front that handles TLS, gzip, and rate limiting. Each of these is a one-liner in Nest but easy to miss.
The procedure
-
Compile with the swc compiler for faster builds (10x over tsc) and set the production build target:
npm install --save-dev @swc/core @swc/cli// nest-cli.json { "compilerOptions": { "builder": "swc" } }NODE_ENV=production npm run build ls dist/main.js -
Configure Nest’s bootstrap for production: enable graceful shutdown, switch to JSON logging, expose Express body limits explicitly:
// src/main.ts import { NestFactory } from '@nestjs/core'; import { Logger, ValidationPipe } from '@nestjs/common'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule, { logger: ['error', 'warn', 'log'], // not 'debug' or 'verbose' in prod bufferLogs: false, }); app.enableShutdownHooks(); // call OnApplicationShutdown app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true })); app.set('trust proxy', 1); // X-Forwarded-* from reverse proxy await app.listen(3000, '127.0.0.1'); // bind to localhost; reverse proxy fronts Logger.log(`listening on ${await app.getUrl()}`); } bootstrap(); -
Add a
/healthendpoint backed by Terminus so the load balancer can drain the node:// src/health/health.module.ts import { Module } from '@nestjs/common'; import { TerminusModule } from '@nestjs/terminus'; import { HealthController } from './health.controller'; @Module({ imports: [TerminusModule], controllers: [HealthController] }) export class HealthModule {}// src/health/health.controller.ts @Controller('health') export class HealthController { constructor(private health: HealthCheckService, private db: TypeOrmHealthIndicator) {} @Get() @HealthCheck() check() { return this.health.check([() => this.db.pingCheck('db', { timeout: 1500 })]); } } -
Run the process under a supervisor. systemd is the simplest, PM2 cluster mode is the second option. A unit file at
/etc/systemd/system/myapp.service:[Unit] Description=NestJS app After=network.target [Service] Type=simple User=node WorkingDirectory=/srv/myapp EnvironmentFile=/etc/myapp/env ExecStart=/usr/bin/node dist/main.js Restart=on-failure RestartSec=5s StandardOutput=journal StandardError=journal [Install] WantedBy=multi-user.target -
Put Nginx in front for TLS termination, gzip, and websocket upgrade if needed:
server { listen 443 ssl http2; ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem; gzip on; gzip_types application/json text/plain; location / { proxy_pass http://127.0.0.1:3000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
Common pitfalls
nest start --prodis the dev CLI in prod mode, not a production launcher. It still importsts-nodeand is slower thannode dist/main.js. Use the latter in systemd and Docker.enableShutdownHooks()is not on by default. Without it,OnApplicationShutdownlifecycle hooks never run and DB connections leak on SIGTERM.- The default Express body parser limit is 100 KiB. POSTing a 2 MiB JSON returns 413. Configure
app.use(json({ limit: '5mb' }))if you actually need larger. - Class-validator and class-transformer must be at runtime, not devDependencies, or
ValidationPipewill crash with “metadata not found” only when a validated DTO is hit. - The Nest CLI in newer versions emits ESM by default if
"type": "module"is set. Mixing with CommonJS dependencies breaks at runtime, not build time. Keep one module system.
For NestJS microservices with non-HTTP transports (gRPC, NATS, Kafka, Redis pub/sub), see NestJS microservices transport. In the engagements Stack Harbor runs, NestJS services are deployed behind Nginx with systemd supervision, the Terminus health endpoint is wired into the LB drain logic, and as part of managed operations we own the rollout — blue/green via the upstream switch, not in-place restart that drops connections.