DEV Community

Cover image for Optimize Docker Size Image with Python Environment
Mangabo Kolawole
Mangabo Kolawole Subscriber

Posted on β€’ Originally published at Medium

6 2

Optimize Docker Size Image with Python Environment

Building Docker image with Python can be well quite heavy.

For a multistage build for example, instead of building wheels at each, you can specify a path for the python environment once it's initialized at the first stage of the build.

ENV PATH="/opt/venv/bin:$PATH"
Enter fullscreen mode Exit fullscreen mode

Make sure you have created the virtual environment tho.πŸ‘€

RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
Enter fullscreen mode Exit fullscreen mode

Here's an example with two steps:

# first stage
FROM python:3.10-slim as builder

WORKDIR /app

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

RUN pip install virtualenv

RUN virtualenv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

COPY requirements.txt .
RUN pip install -r requirements.txt

# another stage
FROM python:3.10-slim

COPY --from=builder /opt/venv /opt/venv

WORKDIR /app

ENV PATH="/opt/venv/bin:$PATH"
Enter fullscreen mode Exit fullscreen mode

Summary

In conclusion, here are the steps again πŸš€:

  • Create the virtual environment in the builder image
  • Copy the virtual environment to the final image

Article posted using bloggu.io. Try it for free.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (3)

Collapse
 
sm0ke profile image
Sm0ke β€’

Nicee ...

Collapse
 
koladev profile image
Mangabo Kolawole β€’

πŸš€

Collapse
 
shy profile image
Shy Ruparel β€’

What's the size difference between doing it one way vs another? Would love a comparison screenshot if you've got one.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up