0

I would like to build packages in slim image and then copy built packages to alpine one. For that I created Dockerfile:

FROM python:3.8.7-slim AS builder

ENV POETRY_VIRTUALENVS_CREATE=false
WORKDIR /app
RUN apt-get update
RUN apt-get install -y build-essential
RUN apt-get install -y libldap2-dev  # for python-ldap
RUN apt-get install -y libsasl2-dev  # for python-ldap
COPY poetry.lock pyproject.toml ./
RUN python -m pip install --upgrade pip && pip install poetry && poetry install --no-dev

FROM python:3.8.7-alpine3.13 AS runtime
COPY --from=builder /root/* /root/
WORKDIR /app
COPY pythonapline .
#RUN python manage.py makemigrations && python manage.py migrate
EXPOSE 8000
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

By default poetry creates virtual environment in directory ~/.cache/pypoetry/virtualenvs (Linux).

When running the runtime image I get import errors. It seems that copied virtual env should be activated or something like that?

1 Answers1

0

The problem is that you are not copying the install packages correctly to the runtime stage. Do note that ENV POETRY_VIRTUALENVS_CREATE=false makes poetry install the dependencies without using a virtual environment.

Try to change this

COPY --from=builder /root/* /root/

to

COPY --from=builder /usr/local/lib/python3.8/site-packages /usr/local/lib/python3.8/site-packages

Also note that you can make better use of cache by separating the installation of poetry itself before running poetry install --no-dev so that you don't have to reinstall poetry after updating the dependencies.

RUN python -m pip install --upgrade pip && pip install poetry
COPY poetry.lock pyproject.toml ./
poetry install --no-dev

However, there is no guarantee that binaries that work on slim will also be compatible with alpine which uses musl libc. Using alpine linux for Python application is discouraged.

PIG208
  • 2,060
  • 2
  • 10
  • 25