Multi-stage Docker build
Multi-stage Docker builds are a feature in Docker that allow you to create more efficient and smaller Docker images by using multiple stages or intermediate containers during the build process. This approach is particularly useful when you need to build complex applications or services that require different tools and dependencies at various stages of development, but you want the final image to be as lightweight as possible.
Here's how multi-stage Docker builds work:
Multiple Build Stages: In a multi-stage Docker build, you define multiple build stages in your Dockerfile. Each stage represents a separate container image with its own set of instructions and dependencies.
Intermediate Images: The first stage, often referred to as the "builder" stage, is used to compile and build your application. It includes all the necessary build tools and dependencies. This stage produces intermediate images.
Copying Artifacts: After the build is complete, you can selectively copy only the necessary artifacts (e.g., compiled binaries or libraries) from the builder stage to the next stage. This reduces the size of the final image.
Final Stage: The final stage is where you create the production-ready Docker image. This stage typically starts from a minimal base image (e.g., Alpine Linux) and only includes the artifacts and runtime dependencies needed to run your application. This results in a much smaller and more secure image compared to including all build tools and intermediate files in the final image.
Create an ec2 instance and install docker on it.
the Dockerfile:
FROM python:3.9
WORKDIR /app
COPY . .
RUN pip install flask
CMD ["python","app.py"]
now, the size of images: the size of normal-multistage image is 1.01GB.
now make stagesin Dockerfile:
#stage 1
FROM python:3.9 AS big-stage
WORKDIR /app
COPY . .
#stage 2
FROM python:3.9-slim-bullseye
COPY --from=big-stage /app /app
RUN pip install flask
CMD ["python","app.py"]
again build the image:
in step 4 it again start from base image
The size of flask-mutlistage is 135 MB whereas the size of normal-multistage is 1.01GB.