Prashant Labs DevLogs
Back to Tutorials
DevOps Beginner

Docker Containerization 101: Multi-Stage Production Builds

Learn how to craft minimal Docker images using multi-stage builds and alpine bases for production deployment.

P
Prashant Sharan
15 mins read

Efficient Docker Containerization

Containerizing web applications ensures build reproducibility across development and production environments.

Step 1: Write a Optimized Dockerfile

Use multi-stage builds to exclude devDependencies and source code from the final runtime image.

# Stage 1: Build phase
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Stage 2: Production runtime
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/package*.json ./
COPY --from=builder /app/dist ./dist
RUN npm ci --only=production

EXPOSE 3000
CMD ["node", "dist/server/entry.mjs"]

Step 2: Build & Verify Image Size

Execute the docker build command and inspect the output size:

docker build -t app:prod .
docker images app:prod
⚠️ Security Note

Always run your node application with a non-root container user (USER node) in production.

Discussions & Comments

🐙 Powered by GitHub Discussions