【问题标题】:Dockerfile RUN merge pip commandsDockerfile RUN 合并 pip 命令
【发布时间】:2018-11-24 19:06:25
【问题描述】:

我有一个看起来像这样的旧 dockerfile

FROM ubuntu:16.04
ENV VISUAL=vim
ENV EDITOR=$VISUAL
ENV TERM=xterm
ENV TERMINFO=/etc/terminfo
ENV PYTHONIOENCODING=utf-8
RUN apt-get --yes update && apt-get --yes upgrade && apt-get --yes install python \
    python-dev \
    python-pip
<...lots of other apt-get install...>
RUN pip install --upgrade pip
RUN pip install -r requirements.txt
<...other staffs>

效果很好,但我想通过减少图层来减小图像大小。所以我合并了最后两行

RUN pip install --upgrade pip && \
 pip install -r requirements.txt

但是构建失败了……

Step 15/45 : RUN pip install --upgrade pip &&  pip install -r requirements.txt
 ---> Running in b96971e60263
Collecting pip
  Downloading https://files.pythonhosted.org/packages/c2/d7/90f34cb0d83a6c5631cf71dfe64cc1054598c843a92b400e55675cc2ac37/pip-18.1-py2.py3-none-any.whl (1.3MB)
Installing collected packages: pip
  Found existing installation: pip 8.1.1
    Not uninstalling pip at /usr/lib/python2.7/dist-packages, outside environment /usr
Successfully installed pip-18.1
Traceback (most recent call last):
  File "/usr/bin/pip", line 9, in <module>
    from pip import main
ImportError: cannot import name main

合并这两行时我错过了什么?

【问题讨论】:

    标签: python docker pip dockerfile


    【解决方案1】:

    假设:在pip install --upgrade pip 中,pip 命令运行是/usr/bin/pip,当它升级pip 时,它会在/usr/local/bin/pip 创建一个新的pip 可执行文件。这个新的可执行文件是 pip install -r requirements.txt 应该运行的,但是当您将它们放在一个 RUN 命令中并因此在单个 shell 实例中运行它们时,shell 对命令位置的缓存启动,因此第二个 pip pip ... &amp;&amp; pip ... 最终从与第一个相同的位置运行,由于新旧版本之间 pip 内部结构的变化而失败。您可以通过在单个 RUN 命令中间插入 hash -d pip 来强制 shell 取消缓存 pip 的位置:

    RUN pip install --upgrade pip && \
     hash -d pip && \
     pip install -r requirements.txt
    

    【讨论】:

    • 哇,我从来没想过。我试过hash -d,但它说/bin/sh: 1: hash: Illegal option -d。如果我删除-d,它会完美运行。
    猜你喜欢
    • 2017-01-22
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    相关资源
    最近更新 更多