PYTHON dockerfile ENTRYPOINT exec 命令无法识别 ENV 变量

时间:2021-07-15 23:45:25

标签: python docker

我觉得我尝试了所有方法,包括使用 shell/exec 表单,但我仍然无法弄清楚为什么 ENV 变量没有被识别。您可以在下面看到我尝试使用的命令的不同变体。 ENV 变量用于默认值,但我计划在运行容器时也可以通过命令行参数更改它们(我目前不确定如何操作)。

# syntax=docker/dockerfile:1 (IS THIS LINE NECESSARY AT ALL NOWADAYS?)

FROM python:3.8-slim-buster

WORKDIR /app

COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt

COPY . .

ENV INPUT="--input ./histogram_input"
ENV OUTPUT="--output ./TEST.tsv"
ENV BUCKET_COUNT="--bucket-count 9999"

ENTRYPOINT ["python", "CreateWeatherHistogram.py", "${INPUT}", "${OUTPUT}", "${BUCKET_COUNT}"]


# ENTRYPOINT ["python", "CreateWeatherHistogram.py", "${input}", "${output}", "${bucket_count}"] # DOESNT WORK
# ENTRYPOINT ["python", "CreateWeatherHistogram.py", "${input} ${output} ${bucket_count}"] # DOESNT WORK
# ENTRYPOINT python CreateWeatherHistogram.py ${input} ${output} ${bucket_count} # DOESNT WORK
# ENTRYPOINT python CreateWeatherHistogram.py "$input" "$output" "$bucket_count" # DOESNT WORK

我的 python 应用程序被调用:

CreateWeatherHistogram --input ./histogram_input --output ./histogram.tsv --bucket-count 5

我希望能够运行这个容器:

docker run --mount type=bind,source=/,target=/app [IMAGE-NAME] --input input.file --output output.file --bucket-count x

1 个答案:

答案 0 :(得分:1)

如果是您自己的 Python 代码,似乎最简单的解决方案就是编写代码以直接从环境中读取值,而不是设置环境变量然后将它们作为参数传入。

例如,考虑以下使用 click 选项处理库(你可以用 argparse(例如参见 this question),但我喜欢与 click 合作:

#!/usr/bin/python

import click
import os


@click.command()
@click.option('--input', envvar='INPUT')
@click.option('--output', envvar='OUTPUT')
@click.option('--bucket-count', envvar='BUCKET_COUNT')
def main(input, output, bucket_count):
    print('value of input:', input)
    print('value of output:', output)
    print('value of bucket_count:', bucket_count)


if __name__ == '__main__':
    main()

可以在命令行上传递参数,如下所示:

$ python CreateWeatherHistogram.py --input histogram_input
value of input: histogram_input
value of output: None
value of bucket_count: None

但是你也可以只设置相应的环境变量:

$ export INPUT=histogram_input
$ python CreateWeatherHistogram.py
value of input: histogram_input
value of output: None
value of bucket_count: None

使用这种代码,您的 Dockerfile 如下所示:

FROM python:3.8-slim-buster

WORKDIR /app

COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt

COPY . .

ENV INPUT="./histogram_input"
ENV OUTPUT="./TEST.tsv"
ENV BUCKET_COUNT="9999"

ENTRYPOINT ["python", "CreateWeatherHistogram.py"]