Skip to main content

Command Palette

Search for a command to run...

Optimize Docker Size Image with Python Environment

Published
1 min readView as Markdown
Optimize Docker Size Image with Python Environment
M

I am a software engineer with 4 years of professional experience, currently specializing in full-stack development.

I work a lot with HTML, CSS, JavaScript, and Python and regularly use React, Vue, and Django to build single-page applications and marketing landing pages.

I also work with React Native to build mobile applications with optimized experiences and for businesses who want to ship products in the market quickly.

Currently, I am a part of a team of 8 as a full-stack engineer where I focus on accessibility, component-driven approaches, and building systems that can scale with ease.

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"

Make sure you have created the virtual environment tho.👀

RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

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"

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.

3 views

More from this blog

koladev

73 posts