# Docker Integration — NestJS: Building Scalable Node.js APIs

Source: https://www.skillbyai.com/en/nestjs/nestjs-docker

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

```dockerfile
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.

```yaml
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=password
```

Quick check

**Quiz:** Why use a multi-stage Dockerfile for a Nest app?

- [ ] To run two servers
- [x] 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.
