What's the difference between Docker and Python virtualenv?

PythonDockerVirtualenv

Python Problem Overview


From what I understand about Docker, it's a tool used for virtual environments. In their lingo, its called "containerization". This is more or less what Python's virtualenv does. However, you can use virtualenv in Docker. So, is it a virtual environment inside a virtual environment? I'm confused as to how this would even work, so could someone please clarify?

Python Solutions


Solution 1 - Python

A virtualenv only encapsulates Python dependencies. A Docker container encapsulates an entire OS.

With a Python virtualenv, you can easily switch between Python versions and dependencies, but you're stuck with your host OS.

With a Docker image, you can swap out the entire OS - install and run Python on Ubuntu, Debian, Alpine, even Windows Server Core.

There are Docker images out there with every combination of OS and Python versions you can think of, ready to pull down and use on any system with Docker installed.

Solution 2 - Python

Python virtual environment will "containerize" only Python runtime i.e. python interpreter and python libraries whereas Docker isolates the whole system (the whole file-system, all user-space libraries, network interfaces) . Therefore Docker is much closer to a Virtual Machine than virtual environment.

Solution 3 - Python

Adding to the above: there is a case for combining docker and venv: some OSs ship with python installed to provide 'OS-near' apps, e.g., to my knowledge, apt on debian (and its derivatives). The python venv enables a developer to ship a python app which requires a different interpreter version without affecting the shipped-with-the-OS python. Now, since Docker 'isolates the whole OS' as stated above, the same applies to a Docker image. Hence, in my view, if a Docker image is required/desired, it is best practice to create a venv inside the Docker image for your python app.

Solution 4 - Python

"a virtual environment, a self-contained directory tree that contains a Python installation for a particular version of Python, plus a number of additional packages"

A docker container provides a higher level of abstraction/isolation, it can has its own "process space, file system, network space, ipc space, etc."

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondanielschnollView Question on Stackoverflow
Solution 1 - Pythonsp0ggView Answer on Stackoverflow
Solution 2 - PythonjilView Answer on Stackoverflow
Solution 3 - PythonBlindfreddyView Answer on Stackoverflow
Solution 4 - PythonMichael.SunView Answer on Stackoverflow