Smaller Docker images with a multi-stage build
Build in one stage and ship only the result in another, so the image leaves out compilers and caches. With examples for Go and Node and how to check the size.
Checked 2026-11-19A Dockerfile that builds an app usually needs a compiler, a package manager and a cache that the running app never uses. In a single-stage build all of that ends up in the image you ship. A multi-stage build uses one image to build and copies only the result into a second, small one.
Go: from about 800 MB to about 15 MB
# Stage 1: build
FROM golang:1.23 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app .
# Stage 2: run
FROM alpine:3.20
RUN adduser -D app
USER app
COPY --from=build /out/app /usr/local/bin/app
ENTRYPOINT ["app"]
Only the last stage becomes the image. COPY --from=build reaches into the earlier stage by its name. CGO_ENABLED=0 makes a static binary that runs on Alpine's musl libc.
Node: install with dev dependencies, ship without them
FROM node:22 AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:22-slim
WORKDIR /app
ENV NODE_ENV=production
COPY package*.json ./
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
USER node
CMD ["node", "dist/server.js"]
Check the result
docker build -t app:multi .
docker images app
docker history app:multi # size added by each layer
Habits that keep images small and builds fast
- Copy the dependency files first, then install, then copy the source. A source change then reuses the cached install layer.
- Add a
.dockerignorewith.git,node_modulesand build output, so they are never sent to the build. - Run as a non-root user in the final stage (
USER). - Build one stage on its own to debug it:
docker build --target build .