Docker

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.

Building Slim Images with Docker Multi-Stage Builds
Table of contents
  1. The problem
  2. The fix: separate building from running
  3. Complementary rules
  4. Measure the result

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_modules and 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.json and run npm ci first, then COPY . .. 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.

About the author

Sina Farahmand

DevOps and back-end developer, into automation, CI/CD and command-line tools. If he has to do something twice, he writes a script for it.

All articles by Sina Farahmand

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.

Leave a comment