Lesson 27 / 34
Docker Integration
Containerize NestJS with a multi-stage Dockerfile and run it with a database using Docker Compose.
Dockerfile
Multi-stage build: compile in one stage, run in a lightweight stage.
FROM node:22-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY --from=builder /app/dist ./dist
EXPOSE 3000
CMD ["node", "dist/main.js"]docker-compose
Spin up NestJS + database with a single command.
services:
app:
build: .
ports:
- "3000:3000"
environment:
- DATABASE_URL=postgres://user:password@db:5432/mydb
depends_on:
- db
db:
image: postgres:16
environment:
- POSTGRES_DB=mydb
- POSTGRES_PASSWORD=passwordQuick check
Quick check: Why use a multi-stage Dockerfile for a Nest app?
- To run two servers
- To compile TypeScript in one stage and ship only dist and prod dependencies
- To avoid needing Node
Answer
To compile TypeScript in one stage and ship only dist and prod dependencies — The final image skips devDependencies and sources, so it is smaller.