Multi-stage builds in Docker are a powerful feature that allows separating build-time and runtime dependencies. This is achieved by using multiple stages in a Dockerfile
, where each stage is built on top of the previous one, but only the final stage is included in the built image. This results in smaller, more secure images with minimal dependencies.
Here’s an example of a Dockerfile
using multi-stage builds:
# Stage 1: Build
FROM node:14-alpine as builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
# Stage 2: Production
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
In this example, the first stage (builder
) is used to build the application, installing all necessary build-time dependencies. The second stage (production
) is used to run the application, with only the runtime dependencies included. The COPY --from=builder
command is used to copy the built artifacts from the first stage to the second stage.
Multi-stage builds can also be used to separate testing and production environments. For example:
# Stage 1: Build
FROM node:14-alpine as builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build && npm test
# Stage 2: Test
FROM node:14-alpine as tester
WORKDIR /app
COPY --from=builder /app /app
RUN npm run test
# Stage 3: Production
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
In this example, the first stage (builder
) is used to build and test the application. The second stage (tester
) is used to run only the tests. The third stage (production
) is used to run the application. This allows for a clear separation of concerns and ensures that the production image only includes the necessary runtime dependencies.
Sources: