Middle
What are multi-stage builds?
sobes.tech AI
Answer from AI
Multi-stage builds are an approach in Docker that allows creating multiple intermediate images within a single Dockerfile to optimize the final image.
The idea is that in the initial stages, the application is built with a full set of tools and dependencies (such as compilers, build libraries), and in the final stage, only the necessary artifacts for running are copied into a minimal image.
Advantages:
- Significantly reduces the size of the final image.
- Simplifies dependency management.
- Increases security by excluding build tools from the final image.
Example Dockerfile with multi-stage build:
# Build stage
FROM ruby:3.0 AS builder
WORKDIR /app
COPY . .
RUN bundle install
RUN rake build
# Final stage
FROM ruby:3.0-slim
WORKDIR /app
COPY --from=builder /app/build /app
CMD ["ruby", "app.rb"]
Here, in the builder stage, all dependencies are installed and the build is performed, and only the ready application without unnecessary tools is included in the final image.