How to use Docker multi-stage builds

· Category: Docker

Short answer

Multi-stage builds use multiple FROM statements in a Dockerfile. Copy only compiled artifacts from build stages into a smaller runtime image. For writing Dockerfiles, see how to write a dockerfile. For building images, see how to build a docker image.

Steps

  1. Start with a build stage: FROM node:18 AS builder
  2. Install dependencies and build the application
  3. Start a runtime stage: FROM node:18-alpine
  4. Copy artifacts: COPY --from=builder /app/dist /app/dist
  5. Build the image: docker build -t myapp:latest .

Tips

  • Use the smallest possible base image for the final stage
  • Do not copy build tools or source code into the runtime image
  • For composing services, see how to use docker compose