Building Slim Images with Docker Multi-Stage Builds
Use two FROM lines to keep build tools out of the final image, plus .dockerignore and layer ordering for better caching.

Table of contents
A good Docker image is small: it pulls quickly, has a smaller attack surface and takes less space in the registry. The main tool for getting there is the multi-stage build: more than one FROM in a single Dockerfile.
The problem
In a single-stage Dockerfile, every build tool (compilers, dev dependencies, caches) stays in the final image. The result is a several-hundred-megabyte image for an application that is only a few megabytes itself.
The fix: separate building from running
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
The first stage has the full build toolchain and produces the output. Only the dist folder is carried into the second stage with COPY --from=build. The final image is just nginx and static files: no node_modules, no compiler.
Complementary rules
- Pick a slim base:
alpine, or distroless where possible. - Have a .dockerignore:
.git,node_modulesand temporary files should never enter the build context. That means smaller builds and no accidental leaks of sensitive files. - Order layers from stable to volatile: copy
package.jsonand runnpm cifirst, thenCOPY . .. With that order, changing one line of code does not reinstall dependencies, and the build cache does its job.
Measure the result
Build the image before and after the change and compare them with docker images. For a typical web app, dropping from hundreds of megabytes to tens is entirely normal, and on servers with slow or expensive bandwidth, such as many in Iran, that saving is felt on every deploy.



Comments
No comments yet. For technical questions, include the details (OS version, the exact error and the command you ran) to get a precise answer.