Why people create virtualenv in a docker container

2020-05-23 05:23发布

问题:

You can build a container with Dockerfile in a few seconds, then why people needs to install a virtual enviroment inside the docker container?

It's like a "virtual machine" in a virtual machine ?

回答1:

I am working with virtualenvs in Docker and I think there are several reasons:

  1. you may want to isolate your app from system's python packages
  2. you may want to run a custom version of python but still keep the system's packages untouched
  3. you may need fine grain control on the packages installed for a specific app
  4. you may need to run multiple apps with different requirements

I think these are all reasonably good reasons to add a little pip install virtualenv at the end of the installation! :)



回答2:

Here is my two cents, or rather comments on @gru 's answer and some of the comments.

  • Neither docker nor virtual environments are virtual machines
  • every line in your docker file produces overhead. But it's true that at runtime virtual environments have zero impact
  • the idea of docker containers is that you have one process which interacts with other (docker-)services in a client-server relationship. Running different apps in one docker or calling one app from another inside a docker is somehow against that idea. More importantly, it adds complexity to you docker, which you want to avoid.
  • "isolating" the python packages that the app sees (inside a virtual environment) from the packages installed in the docker is only necessary if you need to assure a certain version for one or more packages.
  • the system installed inside the container only serves as an environment for the one app that you are running. Adjust it to the requirements of your app. There is no need to leave it "untouched"

So in conclusion: There is no good reason for using a virtual environment inside a container. Install whatever packages you need on the system. If you need control over the exact package versions, install the (docker-wide) with pip or alike.

If you think that you need to run different apps with different package versions inside a single container, take a step back and rethink your design. You are heading towards more complexity, more difficult maintenance and more headache. Split the work/services up into several containers.