Docker
Multi-Stage Build
Build artifacts in one stage and copy them into a slim final image.
By EZ4Code Team
dockerfilemulti-stageoptimization
Code
# Dockerfile
FROM node:20 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY --from=builder /app/dist ./dist
USER node
CMD ["node", "dist/server.js"]
# Result: tiny production image without dev deps and sourceExplanation
Multi-stage builds use multiple FROM lines to keep the final image small by copying only the artifacts needed from earlier stages. The builder stage compiles the code, while the runtime stage carries only production dependencies and the build output. This pattern dramatically reduces image size and attack surface.
More Docker Snippets
Run a Container
Run, list, stop, and remove Docker containers.
Writing a Dockerfile
Build an image from a Dockerfile with multi-instruction layers.
Image Management
Pull, list, tag, push, and prune images.
Volumes & Bind Mounts
Persist data with named volumes, anonymous volumes, and bind mounts.
Networking
Create networks, attach containers, and expose ports.
Docker Compose
Define and run multi-container apps with compose.