Docker Multi-Stage Builds

Compile in a fat image, ship a tiny runtime image.

  • multi-stage
  • slim image
  • COPY from
  • build target
  • small docker image

Docker Multi-Stage Builds

Compile in a fat image, ship a tiny runtime image.

Commands

CommandWhat it does
FROM node:22 AS buildFirst stage: full toolchain
RUN npm ci && npm run buildCompile inside the build stage
FROM node:22-alpine AS prodSecond stage: minimal runtime
COPY --from=build /app/dist ./distCopy only build output
docker build --target build -t app:debug .Build just the debug stage

Example

FROM node:22 AS build
WORKDIR /app
COPY . .
RUN npm ci && npm run build
FROM node:22-alpine AS prod
WORKDIR /app
COPY --from=build /app/dist ./dist
CMD ["node", "dist/server.js"]

FAQ

How much smaller do images get?

Typically 5-10x: toolchains and caches stay in the build stage, only dist plus prod deps ship.

Can stages share files?

Yes via COPY --from=<stage>; stages can also inherit (FROM base AS ...) to share setup steps.

FAQ

How much smaller do images get?
Typically 5-10x: toolchains and caches stay in the build stage, only dist plus prod deps ship.
Can stages share files?
Yes via COPY --from=<stage>; stages can also inherit (FROM base AS ...) to share setup steps.

Docker