【问题标题】:Cache PIP packages in dockerfile在 dockerfile 中缓存 PIP 包
【发布时间】:2017-09-27 09:10:15
【问题描述】:

我正在尝试为我的 python 项目设置 docker,它使用虚拟环境并在 requirements.txt 中定义了一些依赖项。

我也设置了docker-compose,它使用Dockerfile 使用命令docker-compose up --build 构建我的项目映像

我的 Dockerfile:

FROM ubuntu:16.04
 FROM python:3.5  
MAINTAINER ****  

ADD . /core-proejct
WORKDIR /core-project
RUN pip3 install virtualenv
RUN . /bin/activate
RUN pip install -r requirements.txt

所以,每次我尝试构建映像时,它都会从requirements.txt 安装所有 pip 模块。

无论如何我可以缓存 pip 模块并在构建图像时使用缓存的版本。

【问题讨论】:

    标签: python-3.x docker pip docker-compose dockerfile


    【解决方案1】:

    首先,您的 dockerfile 中的 FROM ubuntu:16.04 是多余的,因为单个映像只能有一个上游。

    解决问题的简单方法是在添加项目之前将 pip 命令移至,这样更改项目不会使整个缓存失效。

    最后,你真的不需要在容器中使用 virtualenv,否则你may be doing something wrong

    例如:

    FROM python:3.5
    
    # MAINTAINER is deprecated. Use LABEL instead.
    LABEL maintainer "your info here"
    
    WORKDIR /core-project
    
    ADD ./requirements.txt .
    RUN pip install -r requirements.txt
    
    # Add everything else now.
    ADD . .
    

    【讨论】:

    • ADD . . 会遇到更少的问题
    • 我听到了关于在容器内使用 virtualenv 的不同意见。尽管毫无疑问每个容器都应该有一个理想的用途,但仍有很多人选择使用 virtualenv 将应用程序依赖项与操作系统依赖项进一步分离,即使在 docker 容器中也是如此。
    • 请注意,当使用 COPY 而不是 ADD 时,这不起作用
    • @VME 我的观察不能证实这一点。 COPY 工作得相当好并且更可取,因为它的用例更窄(没有 URL 源,没有存档解包)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 2016-07-21
    • 2018-11-27
    • 2019-10-05
    • 2021-05-16
    • 2022-12-15
    相关资源
    最近更新 更多