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
- Start with a build stage:
FROM node:18 AS builder - Install dependencies and build the application
- Start a runtime stage:
FROM node:18-alpine - Copy artifacts:
COPY --from=builder /app/dist /app/dist - 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