Shrinking Images with Docker Multi-Stage Builds
Procedures / docker-multistage.html
Keep only build tools where needed so the final image stays small.
๐ฌ Splitting build and run images keeps the final image light.
Procedure
- Install dependencies and compile in the build stage.
- Copy only the artifacts and runtime into the run stage.
Example Dockerfile
# stage 1: build
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# stage 2: run
FROM node:20-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build /app/dist ./dist
COPY package*.json ./
RUN npm ci --omit=dev
CMD ["node", "dist/server.js"]
Build and check
docker build -t myapp .
docker images myapp # compare sizes
docker run --rm -p 3000:3000 myapp
When it fails
- File not found: ensure the
COPY --from=buildpath matches the build output. - Missing .dockerignore: copying node_modules bloats the image and slows builds.
Sources
- Official docs Multi-stage builds โ Official docs
- GitHub nodejs/docker-node โ Official Node image
Verified date indicates freshness. Check applicability conditions for older material.