Home > front end >  How to run a venv in the docker?
How to run a venv in the docker?

Time:11-17

My Dockerfile

FROM python:3.7 AS builder
RUN python3 -m venv /venv

COPY requirements.txt .

RUN /venv/bin/pip3 install -r requirements.txt
FROM python:3.7

WORKDIR /home/sokov_admin/www/bot-telegram

COPY . .

CMD ["/venv/bin/python", "./bot.py"]

When I run the docker image I have this error:

docker: Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "/venv/bin/python": stat /venv/bin/python: no such file or directory: unknown.

What should I change in my code?

CodePudding user response:

The example you show doesn't need any OS-level dependencies for Python dependency builds. That simplifies things significantly: you can do things in a single Docker build stage, without a virtual environment, and there wouldn't be any particular benefit from splitting it up.

FROM python:3.7
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["./bot.py"]

The place where a multi-stage build with a virtual environment helps is if you need a full C toolchain to build Python libraries. In this case, in a first stage, you install the C toolchain and set up the virtual environment. In the second stage you need to COPY --from=... the entire virtual environment to the final image.

# Builder stage:
FROM python:3.7 AS builder

# Install OS-level dependencies
RUN apt-get update \
 && DEBIAN_FRONTEND=noninteractive \
    apt-get install --no-install-recommends --assume-yes \
      build-essential
    # libmysql-client-dev, for example

# Create the virtual environment
RUN python3 -m venv /venv
ENV PATH=/venv/bin:$PATH

# Install Python dependencies
WORKDIR /app
COPY requirements.txt .
RUN pip3 install -r requirements.txt

# If your setup.py/setup.cfg has a console script entry point,
# install the application too
# COPY . .
# RUN pip3 install .

# Final stage:
FROM python:3.7 # must be _exactly_ the same image as the builder

# Install OS-level dependencies if needed (libmysqlclient, not ...-dev)
# RUN apt-get update && apt-get install ...

# Copy the virtual environment; must be _exactly_ the same path
COPY --from=builder /venv /venv
ENV PATH=/venv/bin:$PATH

# Copy in the application (if it wasn't `pip install`ed into the venv)
WORKDIR /app
COPY . .

# Say how to run it
EXPOSE 8000
CMD ["./bot.py"]
  • Related