Is there a way to automatically activate a virtualenv as a docker entrypoint?

Try:

docker exec <container> sh -c 'source venv/bin/activate; flask <sub command>'

Your command can be:

CMD sh -c 'source venv/bin/activate; gunicorn...'

As an alternative to just sourcing the script inline with the command, you could make a script that acts as an ENTRYPOINT. An example entrypoint.sh would look something like:

#!/bin/bash
source venv/bin/activate
exec "$@"

Then in your Dockerfile you would copy this file and set it as the ENTRYPOINT:

FROM myimage
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

Now you can run it like docker run mynewimage flask <sub command> or docker run mynewimage gunicorn.


You don't need to activate the env. Prepend /path/to/virtualenv/bin to $PATH, then python, pip, etc. automatically point to the commands in the virtualenv.

FROM python:3.4-alpine
WORKDIR /deps
ENV PATH=/virtualenv/bin:$PATH
RUN pip install virtualenv && \
    mkdir virtualenv && \
    virtualenv /virtualenv
COPY . /deps

Example working:

#Build dockerfile
docker build . -t="venv_example"
#Run all python commands in virtualenv w/ no hassle
docker run --rm venv_example which python
>/virtualenv/bin/python
docker run --rm venv_example which pip
>/virtualenv/bin/pip

Tags:

Python

Docker