python - Docker 和 pip 安装 : avoid installing all packages when some are already installed

标签 python docker pip docker-compose

我正在使用 docker compose 构建 Python 项目的堆栈。这是一个处理要求的 dockerfile 片段。

# Requirements are installed here to ensure they will be cached.
COPY ./requirements /requirements
RUN pip install --no-cache-dir -r /requirements/production.txt \
    && rm -rf /requirements

使用该配置,我可以缓存需求,但是当我修改 生产.txt 时(例如更新单个包),Docker 会重新安装所有内容。

我知道 Docker 需要创建一个新的容器,但有没有办法避免再次重新安装所有内容,而只安装必要的内容?

最佳答案

在这种情况下,不,没有办法避免重新安装 product.txt 中的所有内容。

来自official docs ,在利用构建缓存部分:

For the ADD and COPY instructions, the contents of the file(s) in the image are examined and a checksum is calculated for each file. The last-modified and last-accessed times of the file(s) are not considered in these checksums. During the cache lookup, the checksum is compared against the checksum in the existing images. If anything has changed in the file(s), such as the contents and metadata, then the cache is invalidated

由于您更改了 production.txt,缓存将失效,并且 docker 从之前有效的层启动并安装所有内容。

现在,如果您有多个 requirements.txt 文件,您可以通过执行单独的复制和安装步骤来利用一些缓存:

COPY requirements1.txt
RUN pip install --no-cache-dir -r requirements1.txt

COPY requirements2.txt
RUN pip install --no-cache-dir -r requirements2.txt

这可能还有其他缺 pip ,但它可以让您通过将不太可能更新的长期软件包放入 requirements1.txt 中并将不太稳定的软件包放入 中来部分减少重新安装时间>requirements2.txt。更改 requirements2.txt 只会导致重新安装这些需求。

但是,作为警告,这也意味着更改 requirements1.txt 将完全需要重新安装 requirements2.txt,因为它出现在 >requirements1.txt 步骤。这与一个文件的原始行为没有什么不同,但要知道这里的顺序很重要。这种流程还有一些其他缺 pip ,但它们相当迂腐。

关于python - Docker 和 pip 安装 : avoid installing all packages when some are already installed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55236023/

相关文章:

azure - Docker 永远不会在 Azure 上运行 - 等待对容器预热请求的响应

python - boto3 python 2.7 ImportError : No module named boto3 USER_BASE USER_SITE site packages doesn't exist

python - 使用 PyPI + OS 级依赖项打包 Python 应用程序

python - pip 错误 : Bad interpreter when trying to run 'pip install ...' on OS X

python - 在numpy中获得matrix < matrix结果的最快方法是什么?

python - IDLE 不会突出显示我的语法

docker - 服务未就绪 : gitlab-managed-apps/ingress-nginx-ingress-controller

python - VS代码: ANSI Colors in Terminal

Python 中的 Define_method 等效项

java - 当我尝试使用自定义端口从 java 连接时,Docker 中的 RabbitMQ 抛出异常