Dockerfile Multi-Stage Build
Multi-stage Dockerfile for Node.js with build, prune, and minimal production image layers.
# Dockerfile
FROM node:20-alpine AS base
WORKDIR /app
COPY package.json package-lock.json ./
# Install dependencies
FROM base AS deps
RUN npm ci --ignore-scripts
# Build application
FROM base AS build
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
# Production dependencies only
FROM base AS prod-deps
RUN npm ci --omit=dev --ignore-scripts
# Final production image
FROM node:20-alpine AS runner
WORKDIR /app
RUN addgroup --system app && adduser --system --ingroup app app
COPY --from=prod-deps --chown=app:app /app/node_modules ./node_modules
COPY --from=build --chown=app:app /app/dist ./dist
COPY --from=build --chown=app:app /app/package.json ./
USER app
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1
CMD ["node", "dist/server.js"]Sponsored
Docker Desktop — Container development made easy
Use Cases
- Optimized Docker images for production
- Reducing image size with multi-stage builds
- Secure containerized Node.js applications
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Docker Compose Multi-Service Setup
Docker Compose configuration for a Node.js app with PostgreSQL, Redis, and Nginx reverse proxy.
Redis Docker Setup with Persistence
Docker Compose for Redis with persistence, password auth, memory limits, and a health check.
PostgreSQL Docker Setup with Init Script
Docker Compose for PostgreSQL with volume persistence, init scripts, and connection pooling.
GitHub Actions Docker Build and Push
GitHub Actions workflow to build a Docker image and push it to GitHub Container Registry on release.