【问题标题】:Pass an empty value to Docker's build-args将空值传递给 Docker 的 build-args
【发布时间】:2020-10-13 09:56:01
【问题描述】:

假设我有这个 python 脚本 main.py:

import sys
if not sys.argv[1]:
    print('Empty')
    sys.exit()
print('Otherwise')

如果我像这样运行它 python3 main.py '',它会打印 Empty

如果我像这样运行它python3 main.py 45,它会打印 Otherwise

现在假设我要构建一个运行此脚本的 Docker 映像。这是我的 Dockerfile:

FROM python:3.6-slim
ARG A_VARIABLE

WORKDIR /
COPY main.py /

RUN python3 main.py ${A_VARIABLE}

如果我使用此命令 docker build --build-arg A_VARIABLE=45 构建我的映像。 它工作正常。

Sending build context to Docker daemon  1.905MB
Step 1/5 : FROM python:3.6-slim
 ---> c36a97a24d09
Step 2/5 : ARG A_VARIABLE
 ---> Using cache
 ---> e9146c21f196
Step 3/5 : WORKDIR /
 ---> Using cache
 ---> 942a7511c60d
Step 4/5 : COPY main.py /
 ---> Using cache
 ---> 96bd3882233a
Step 5/5 : RUN python3 main.py ${A_VARIABLE}
 ---> Using cache
 ---> 4c9f0b1b997c
Successfully built 4c9f0b1b997c

如果我像这样构建它 docker build --build-arg A_VARIABLE='' . 它会失败。

Sending build context to Docker daemon  1.905MB
Step 1/5 : FROM python:3.6-slim
 ---> c36a97a24d09
Step 2/5 : ARG A_VARIABLE
 ---> Using cache
 ---> e9146c21f196
Step 3/5 : WORKDIR /
 ---> Using cache
 ---> 942a7511c60d
Step 4/5 : COPY main.py /
 ---> Using cache
 ---> 96bd3882233a
Step 5/5 : RUN python3 main.py ${A_VARIABLE}
 ---> Running in e1b5dab971d2
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    if not sys.argv[1]:
IndexError: list index out of range
The command '/bin/sh -c python3 main.py ${A_VARIABLE}' returned a non-zero code: 1

是否有任何解决方法,以便我可以将空值作为 build-args 传递?

【问题讨论】:

    标签: python python-3.x docker dockerfile


    【解决方案1】:

    在 shell 中(因此在 Dockerfile RUN 语句中)一个未加引号的空变量会直接消失。

    RUN python3 main.py "${A_VARIABLE}"
    

    另见When to wrap quotes around a shell variable?

    【讨论】:

      【解决方案2】:
      import sys
      if len(sys.argv) > 1:
          print('Empty')
          sys.exit()
      print('Otherwise')
      

      在 python 代码中,而不是使用 argv[1],检查传递的命令行参数数组的长度。 这样,您可以在 docker 命令中传递空参数。

      【讨论】:

        猜你喜欢
        • 2021-09-11
        • 1970-01-01
        • 2019-12-30
        • 1970-01-01
        • 1970-01-01
        • 2015-02-10
        • 1970-01-01
        • 2019-10-25
        • 1970-01-01
        相关资源
        最近更新 更多