• Email Address: forum@outsourcepath.com
  • English
Topics related to activate python virtualenv

Activate python virtualenv in Dockerfile - How to perform it ?

This article covers how to Activate python virtualenv in Dockerfile.

Basically, to package Python application in a Docker image, we often use virtualenv. However, to use virtualenv, we need to activate it.
Therefore, there is no point in using virtualenv inside a Docker Container unless you are running multiple apps in the same container, if that's the case I'd say that you're doing something wrong and the solution would be to architect your app in a better way and split them up in multiple containers.

There are perfectly valid reasons for using a virtualenv within a container.
You don't necessarily need to activate the virtualenv to install software or use it.
Try invoking the executables directly from the virtualenv's bin directory instead:

FROM python:2.7
RUN virtualenv /ve
RUN /ve/bin/pip install somepackage
CMD ["/ve/bin/python", "yourcode.py"]

One solution is to explicitly use the path to the binaries in the virtualenv.

In this case we only have two repetitions, but in more complex situations you’ll need to do it over and over again.
Besides the lack of readability, repetition is a source of error.
As you add more calls to Python programs, it's easy to forget to add the magic /opt/venv/bin/ prefix.
It will (mostly) work though:
FROM python:3.8-slim-buster
RUN python3 -m venv /opt/venv
# Install dependencies:
COPY requirements.txt .
RUN /opt/venv/bin/pip install -r requirements.txt
# Run the application:
COPY myapp.py .
CMD ["/opt/venv/bin/python", "myapp.py"]
The only caveat is that if any Python process launches a sub-process, that sub-process will not run in the virtualenv.

Recent Post