在 docker 容器内的 virtualenv 中 运行 django 应用程序的目的是什么?

What is the purpose of running a django application in a virtualenv inside a docker container?

docker django 应用程序中的 virtualenv 的用途是什么? Python和其他依赖已经安装好了,但是同时需要用pip安装很多包,所以貌似冲突还不清楚。

你能解释一下这个概念吗?

编辑:另外,例如。我在 docker django 应用程序中创建了 virtualenv,最近安装了 pip freeze djangorestframework 并将其添加到 installed in settings.py 但 docker-compose up 引发错误 . No module named rest_framework.Checked,一切正确.Docker/virtualenv冲突?可能是?

virtualenv 用于将包隔离到特定环境。 Docker 也用于将设置隔离到特定环境。所以本质上,如果你使用 docker ,那么使用 virtualenv 也没有太多好处。

只需将 pip install thing 直接安装到 docker 环境中,它不会造成任何伤害。要 pip 安装要求,请使用 docker 文件,您可以在其中执行命令。

您可以在下面找到伪代码示例。

FROM /path/to/used/docker/image
RUN pip install -r requirements.txt

Docker 和容器化可能会激发您不需要虚拟环境的错觉。 distutil 的 Glpyh 对这种误解提出了一个非常有说服力的论据 in this pycon talk

virtualenv 优点的相同基本方面适用于容器,因为它们适用于非容器化应用程序,因为从根本上说,您仍然 运行 宁 linux 分布。

Debian and Red Hat are fantastically complex engineering projects. Integrating billions of lines of C code.For example, you can just apt install libavcodec. Or yum install ffmpeg.

Writing a working build system for one of those things is a PhD thesis. They integrate thousands of Python packages simultaneously into one working environment. They don't always tell you whether their tools use Python or not.

And so, you might want to docker exec some tools inside a container, they might be written in Python, if you sudo pip install your application in there, now it's all broken.

So even in containers, isolate your application code from the system's

无论您是否使用 docker,您都应该始终 运行 在虚拟环境中应用。

现在 docker 特别是使用 virtualenv 比它应该的要复杂一些。在 docker 中,每个 RUN 命令 运行 都是孤立的,除了文件系统更改之外,没有其他状态逐行保留。要安装到 virutalenv,您必须预先激活 command on every line:

RUN apt-get install -y python-virtualenv
RUN virtualenv /appenv
RUN . /appenv/bin/activate; \
    pip install -r requirements.txt

ENTRYPOINT . /appenv/bin/activate; \
           run-the-app