在Dockerfile中定制ONBUILD环境

13

我稍微修改了这个Dockerfile来支持我的特定用例: 我需要指定自己的PyPi服务器, 我们发布内部库的地方。通常可以通过指定pip.conf文件或通过向pip传递命令行选项来实现。

我正在尝试使用以下内容:

FROM python:3.5

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

ONBUILD COPY requirements.txt /usr/src/app/

# 1st try: set the env variable and use it implicitely. Does not work!
# ENV PIP_CONFIG_FILE pip.conf
# ONBUILD RUN pip install --no-cache-dir -r requirements.txt

# 2nd try: set once the env variable, just for this command. Does not work!
# ONBUILD RUN PIP_CONFIG_FILE=pip.conf pip install --no-cache-dir -r requirements.txt

# 3rd try: directly configure pip. Works, but these values should not be set in the Dockerfile!
ONBUILD RUN pip install --index-url http://xx.xx.xx.xx:yyyyy --trusted-host xx.xx.xx.xx --no-cache-dir -r requirements.txt

ONBUILD COPY . /usr/src/app

我的pip.conf非常简单,在Docker之外使用时有效:

[global]
timeout = 60
index-url = http://xx.xx.xx.xx:yyyyy
trusted-host = xx.xx.xx.xx

链接:

  • DockerfileENV 文档在这里
  • pip 配置文档在这里

我有以下问题:

  • 为什么 ENV 不起作用?
  • 为什么在 RUN 命令中显式设置变量不起作用?
  • 这些问题是与 ONBUILD 或者 RUN 有关吗?
2个回答

25

我遇到了同样的问题,通过将以下内容添加到Dockerfile中,我成功解决了它:

COPY pip.conf pip.conf
ENV PIP_CONFIG_FILE pip.conf
RUN pip install <my_package_name>

pip.conf 文件的结构如下:

[global]
timeout = 60
index-url = https://pypi.org/simple
trusted-host = pypi.org
               <my_server_page>
extra-index-url = https://xxxx:yyyy@<my_server_page>:<package_location>

我发现这是Docker从pypi服务器找到软件包的唯一方法。希望这个解决方案可以普遍适用并帮助其他遇到这个问题的人。


2
ONBUILD指令会在构建镜像时添加触发指令,以便在将镜像用作另一个构建的基础时执行。根据文档,在1.4版本之前,ONBUILD指令不支持环境变量,即使与上述任何指令结合使用也是如此。如果使用docker 1.4+版本,请尝试以下操作(如问题15025所示)。
ONBUILD ENV PIP_CONFIG_FILE pip.conf

好主意,但似乎不起作用 :(. 我的Docker版本是Docker version 1.11.2, build b9f10c9 - blueFast
这条评论的格式可能有误,但变量确实已经设置:Step 2 : RUN echo ${PIP_CONFIG_FILE} ---> Running in a5fc69f16f32 pip.conf - blueFast
这些环境变量被标记为导出吗?pip应该看到它们吗?似乎它没有看到。 - blueFast
如果echo能看到变量,那么pip也应该能看到,除非它是由ONBUILD RUN调用的。 - VonC
@Roelant 不确定:您可以在问题下面留言,这将通知原帖作者。 - VonC
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接