skip to Main Content

I using the volume mount to directly readAndWrite the host’s python venv file in docker container, if the host is already active this venv file, is it need to active this file again in docker container?

2

Answers


  1. It depends on how you define the Dockerfile.
    For example, if you set the appropriate environment variables (the one of the Virtual Environment and the Path) you don’t need to activate it every time and it’s already activated inside the container.

    A simple Dockerfile can be the following:

    FROM python:3.9-slim-bullseye
    
    ENV VIRT_ENV=/opt/venv
    RUN python3 -m venv $VIRT_ENV
    ENV PATH="$VIRT_ENV/bin:$PATH"
    
    COPY app.py .
    CMD ["python", "app.py"]
    

    In this case, the virtualenv works for all the commands specified in the Dockerfile.

    You can check the activation executing the container in interactive mode docker run -it test bash and with the command pip -V you’ll get something like

    pip 23.0.1 from /opt/venv/lib/python3.9/site-packages/pip (python 3.9)
    

    where it’s specified the path of the virtualenv.

    Login or Signup to reply.
  2. You can’t do this. If you already have a virtual environment with your application installed in it, just run it.

    There are two problems you’ll run into. The first is that a container has an isolated filesystem, so the container can’t see the files in the host virtual environment. The second is that a virtual environment is extremely specific to a single Python build. In comments you hint at an Alpine-based container; a different Python built on a different C library is likely to hit things like "segmentation fault" errors.

    If you do have a hard size limit, and your Python-related dependencies do exceed it, you might not be able to use Docker here. In principle it would be possible to hand-build an environment that ran on Docker but kept the entire library stack on the host, but it would be hard to maintain and the advantages over a non-Docker virtual environment are unclear to me.

    (I believe a Debian-based Python image can use precompiled "wheel" format Python packages, where an Alpine image can’t; it may turn out here that a Debian-based image is actually smaller and faster to build.)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search