Deployment Basics
Build to JavaScript, run the compiled output, and configure the app through environment variables.
Syntax
npm run build && npm run start:prodDeploying a Nest app means compiling TypeScript to JavaScript and running the result with Node.js in production.
The steps
npm run buildcompilessrc/into thedist/folder.node dist/main.js(ornpm run start:prod) runs the compiled app.- Provide configuration through environment variables, not code.
Production checklist
- Set
NODE_ENV=production. - Read the port from the environment:
app.listen(process.env.PORT ?? 3000). - Disable ORM
synchronizeand use migrations. - Enable a global ValidationPipe and sensible CORS.
Example
# Build the project
npm run build
# Run the compiled output in production
npm run start:prod
# equivalent to: node dist/main.js
# Provide config via environment variables
NODE_ENV=production PORT=8080 node dist/main.jsWhen to use it
- A developer runs `npm run build` to compile TypeScript to dist/ and then `node dist/main.js` to start the production server without the Nest CLI.
- A team containerizes the NestJS app with a multi-stage Dockerfile so only the compiled dist/ and production node_modules are included in the image.
- An engineer sets PORT and DATABASE_URL as environment variables in the hosting platform so the app reads them via ConfigService at runtime.
More examples
Build and run for production
Compiles the project and starts the output directly with Node, bypassing ts-node and the Nest CLI for a leaner production start.
# Build TypeScript to JavaScript
npm run build
# Start the compiled output
node dist/main.js
# Or with pm2 for process management
pm2 start dist/main.js --name my-apiMulti-stage Dockerfile
Uses a two-stage build to compile in the first stage and copy only the compiled dist/ and production dependencies into the slim final image.
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
EXPOSE 3000
CMD ["node", "dist/main.js"]Health-check endpoint
Adds a lightweight /health endpoint that container orchestrators (Docker, Kubernetes) can poll to verify the app is running.
import { Controller, Get } from '@nestjs/common';
@Controller('health')
export class HealthController {
@Get()
check() {
return { status: 'ok', timestamp: new Date().toISOString() };
}
}
Discussion