Skip to main content
 首页 » 编程设计

python之在 dockerfile 中自定义 ONBUILD 环境

2024年08月22日34birdshome

我正在稍微修改 this 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 

链接:

  • Dockerfile 的 ENV 已记录 here
  • pip 配置已记录 here

我有以下问题:

  • 为什么 ENV 不工作?
  • 为什么在 RUN 命令中显式设置变量不起作用?
  • ONBUILD 或 RUN 是否存在这些问题?

请您参考如下方法:

我遇到了同样的问题,我设法将其添加到 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 服务器找到包的方法。我希望这个解决方案是通用的,可以帮助其他遇到这个问题的人。