Skip to main content

Command Palette

Search for a command to run...

Multistage Docker Build Using-Flask App

Published
2 min read

Multistage Docker builds are a technique to create smaller and more efficient Docker images by dividing the build process into stages. Instead of using a single Dockerfile for the entire build, multiple stages are defined.

The initial stages focus on building the application, while the final stage generates a lightweight image by copying only necessary artifacts from the preceding stages.

Single-Stage Build:

  1. Clone the repository and navigate to the project directory:
git clone https://github.com/vishalparit10/python-multistage-docker
cd python-multistage-docker
  1. Examining the traditional Dockerfile for a Python Flask application without using the multistage approach:

     FROM python:3.9
    
     WORKDIR /app
    
     COPY backend/ /app
    
     RUN pip install -r requirements.txt
    
     EXPOSE 5000
    
     CMD ["python","app.py"]
    

    This Dockerfile performs all the tasks in a single stage, resulting in an image that may include unnecessary dependencies and artifacts, leading to larger image sizes.

  2. Build the image:

sudo docker build -t python-flask-app .
  1. Check the image size:
docker images

Multistage Docker Build:

Now, let's optimize the Dockerfile using a multistage approach:

# Stage 1: Build the Flask Application
FROM python:3.9 AS backend-builder

WORKDIR /app

COPY backend/requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

RUN pip install Flask

COPY backend/ .

# Stage 2: Final Image
FROM python:3.9-slim-buster

WORKDIR /app

COPY --from=backend-builder /app /app

RUN pip install Flask

EXPOSE 5000

CMD ["python", "app.py"]

Multistage Build:

  1. Build the multistage image using above Dockerfile (Remove old Dockerfile and create new one with above code):
sudo docker build -t multistage-app .
  1. Check the multistage image size:
docker images

Run the Container:

  1. Run the container:
sudo docker run -d -p 5000:5000 multistage-app:latest

Verify the application on your browser by navigating to http://instance_id:5000.