NestJS course Β· Module 12: Containers and CI/CD
Dockerfile for NestJS - Building the Camp
In this lesson5
Legionary, it is time to learn how to write camp construction instructions - that is, a Dockerfile! A Dockerfile is a text file containing a sequence of commands that Docker executes to build an image. Each command creates a new layer (stratum) in the image.
Basic Dockerfile Instructions
A Dockerfile consists of instructions, each serving a specific role:
FROM - Foundation of the Camp
The FROM instruction selects the base image on which we build. For NestJS applications we use the Node.js image:
# We use the official Node.js image in Alpine version (lightweight!)
FROM node:20-alpineAlpine Linux is a minimalist distribution - it weighs ~5MB instead of ~900MB for a full Ubuntu. It is like a light field camp instead of a full fortress - quick to set up and move.
WORKDIR - Designating the Construction Site
The WORKDIR instruction sets the working directory inside the container:
# Set the working directory
WORKDIR /appCOPY - Transporting Materials
COPY copies files from our computer into the container:
# Copy package.json and yarn.lock files
COPY package.json yarn.lock ./
# Copy the rest of the source code
COPY . .RUN - Executing Construction Work
RUN executes commands during image build:
# Install dependencies
RUN yarn install --frozen-lockfile
# Build the application
RUN yarn buildCMD - Startup Order
CMD defines the command to run when the container starts:
# Run the application
CMD ["node", "dist/main"]Simple Dockerfile for NestJS
FROM node:20-alpine
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile
COPY . .
RUN yarn build
EXPOSE 4000
CMD ["node", "dist/main"]Multi-stage Build - Advanced Build Strategy
A simple Dockerfile has a problem - the final image contains development tools, TypeScript source files, and devDependencies. It is like leaving scaffolding after the fortress construction is complete.
Multi-stage build allows using multiple build stages, where the final image contains only what is needed to run:
# =========================
# STAGE 1: Builder (Legion Engineers)
# =========================
FROM node:20-alpine AS builder
WORKDIR /app
# Copy dependency files
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile
# Copy source code and build
COPY . .
RUN yarn build
# Install only production dependencies
RUN yarn install --frozen-lockfile --production
# =========================
# STAGE 2: Production (Ready Camp)
# =========================
FROM node:20-alpine AS production
WORKDIR /app
# Copy ONLY the built code and production dependencies
COPY /app/dist ./dist
COPY /app/node_modules ./node_modules
COPY /app/package.json ./package.json
# Create a non-root user
RUN addgroup -g 1001 -S nodejs && \
adduser -S nestjs -u 1001
USER nestjs
EXPOSE 4000
CMD ["node", "dist/main"]Size Comparison
const comparison = {
singleStage: {
size: '~800 MB',
contains: ['node_modules (dev + prod)', 'src/', 'test/', '.git'],
security: 'root user'
},
multiStage: {
size: '~200 MB',
contains: ['dist/', 'node_modules (prod only)', 'package.json'],
security: 'non-root user (nestjs)'
}
};The .dockerignore File
Just as .gitignore prevents adding files to the repository, .dockerignore prevents copying unnecessary files into the image:
node_modules
dist
.git
.gitignore
*.md
.env
.env.*
test
coverage
.vscode
.ideaThanks to .dockerignore, the COPY . . command will not copy these files, speeding up the build and reducing image size.
Building and Running
# Build the image
docker build -t roman-imperium-api:1.0 .
# Run the container
docker run -d -p 4000:4000 --name imperium-api roman-imperium-api:1.0
# Check logs
docker logs imperium-api
# Verify it works
curl http://localhost:4000/healthRemember, legionary - multi-stage build is the best practice for production. We build heavy, but deploy light!
Code for this lesson: src/dockerfile-example.ts
// Dockerfile - Instructions for building a legion camp
console.log("=== DOCKERFILE FOR NestJS ===\n");
// Dockerfile instructions
interface DockerInstruction {
command: string;
purpose: string;
example: string;
}
const instructions: DockerInstruction[] = [
{
command: 'FROM',
purpose: 'Base image (foundation of the camp)',
example: 'FROM node:20-alpine',
},
{
command: 'WORKDIR',
purpose: 'Working directory (construction site)',
example: 'WORKDIR /app',
},
{
command: 'COPY',
purpose: 'Copying files (transporting materials)',
example: 'COPY package.json yarn.lock ./',
},
{
command: 'RUN',
purpose: 'Executing a command (construction work)',
example: 'RUN yarn install --frozen-lockfile',
},
{
command: 'EXPOSE',
purpose: 'Port declaration (camp gate)',
example: 'EXPOSE 4000',
},
{
command: 'CMD',
purpose: 'Startup command (the order to start)',
example: 'CMD ["node", "dist/main"]',
},
];
console.log("Dockerfile instructions:\n");
instructions.forEach(i => {
console.log(`${i.command}: ${i.purpose}`);
console.log(` Example: ${i.example}\n`);
});
// Multi-stage build comparison
console.log("=== MULTI-STAGE BUILD ===\n");
console.log("Single-stage: ~800 MB (dev + prod dependencies)");
console.log("Multi-stage: ~200 MB (only production)\n");
console.log("Stage 1 (builder): install, build, compile");
console.log("Stage 2 (production): COPY --from=builder only dist/");
console.log("\nBenefit: smaller image, no dev-dependencies, non-root user");
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does the FROM instruction define in a Dockerfile?
2. What is the main benefit of multi-stage build in Docker?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Define two Dockerfile stages: builder (building) and production (running)
- Click in order
Arrange the Dockerfile instructions in the correct order:
- Code editor
Select which files/folders should be ignored by Docker (node_modules, dist, .git, .env, src, test, package.json, coverage)
- Horizontal ordering
Arrange the elements of the Docker image build command in the correct order:
Tasks after this lesson
- QuestionReview: The FROM instruction in Dockerfile
- QuestionReview: Purpose of multi-stage build
- Coding taskReview: Multi-stage build in practice
- Click in orderReview: Dockerfile instruction order
- QuestionReview: The role of .dockerignore
- Coding taskReview: .dockerignore configuration
- Put in orderReview: Docker image build command