bashintermediate

Dockerfile Multi-Stage Build

Multi-stage Dockerfile for Node.js with build, prune, and minimal production image layers.

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