Deployment Basics

Build to JavaScript, run the compiled output, and configure the app through environment variables.

Syntaxnpm run build && npm run start:prod

Deploying a Nest app means compiling TypeScript to JavaScript and running the result with Node.js in production.

The steps

  1. npm run build compiles src/ into the dist/ folder.
  2. node dist/main.js (or npm run start:prod) runs the compiled app.
  3. 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 synchronize and use migrations.
  • Enable a global ValidationPipe and sensible CORS.

Example

Example Β· bash
# 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.js

When 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.

Example Β· bash
# 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-api

Multi-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.

Example Β· dockerfile
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.

Example Β· ts
import { Controller, Get } from '@nestjs/common';

@Controller('health')
export class HealthController {
  @Get()
  check() {
    return { status: 'ok', timestamp: new Date().toISOString() };
  }
}

Discussion

  • Be the first to comment on this lesson.