Optimizing Docker Images: A Guide to Multi-Stage Builds

 

In my previous blog, I showed how to build an image from a Dockerfile. Sometimes, the image size can get quite large, even several gigabytes, which can be hard to manage on systems with limited storage. I found a solution to this issue by using a multi-stage Dockerfile.

The idea is simple: We split the Dockerfile into two stages, and use the output of the first stage in the second stage. In the first stage, we install dependencies and libraries. In the second stage, we copy the necessary files and libraries from the first stage.

Let’s break it down with this Dockerfile template:

# Base Image
# Stage 1
FROM python:3.11 AS backend-builder # Use the full Python 3.11 image and name it "backend-builder"

WORKDIR /app # Set the working directory

# Copy project files
COPY . . # Copy files from the current directory to the container

# Install required libraries
RUN pip install -r requirements.txt # Install dependencies listed in requirements.txt

# Stage 2
FROM python:3.11-slim # Use a slim version of the Python 3.11 image to reduce image size

WORKDIR /app # Set the working directory

# Copy installed packages and application code from the first stage
COPY --from=backend-builder /usr/local/lib/python3.11/ /usr/local/lib/python3.11
COPY --from=backend-builder /app /app

# Command to run the application
CMD ["python", "app.py"]

Explanation:

  • Stage 1: We use the full Python 3.11 image and install the required libraries.
  • Stage 2: We use the slimmer version of the Python image and only copy the necessary files and libraries from the first stage. This helps in reducing the overall image size.

Here is the YouTube Link: https://youtube.com/@raeesq.?si=v_QK6Q2XXMf9mKep

This way, the image becomes smaller, as we’re not carrying unnecessary dependencies from the first stage into the final image.

I hope this blog helps you understand the multi-stage Dockerfile approach. Don’t forget to share it with others and check out my videos for more tips. Stay connected!

Comments

Popular posts from this blog

📘 Understanding Prometheus in a Simple Way-Part 3 (For DevOps Beginners)

Grafana Setup & Dashboard Creation (Part-5)— Explained by Raees Yaqoob Qazi

My First Python Program: A Simple Calculator