【问题标题】:Run docker image with json file as variable使用 json 文件作为变量运行 docker 镜像
【发布时间】:2023-02-08 03:05:55
【问题描述】:

我有以下码头图像

FROM python:3.8-slim

WORKDIR /app

# copy the dependencies file to the working directory
COPY requirements.txt .
COPY model-segmentation-512.h5 .
COPY run.py .


# TODO add python dependencies

# install pip deps
RUN apt update
RUN pip install --no-cache-dir -r requirements.txt

RUN mkdir /app/input
RUN mkdir /app/output

# copy the content of the local src directory to the working directory
#COPY src/ .

# command to run on container start
ENTRYPOINT [ "python", "run.py"] 

然后我想使用以下命令运行我的图像,其中 json_file 是一个我可以随时在我的机器上更新的文件,run.py 将读取它以导入 python 脚本所需的所有参数:

docker run -v /local/input:/app/input -v /local/output:/app/output/ -t docker_image python3 run.py model-segmentation-512.h5 json_file.json

但是,当我这样做时,我得到一个 FileNotFoundError: [Errno 2] No such file or directory: 'path/json_file.json',所以我认为我没有正确引入我的 json 文件。我应该更改什么以允许我的 docker 图像在每次运行时读取更新的 json 文件(就像变量一样)?

【问题讨论】:

  • 你能在不涉及 Docker 的情况下在 Python 虚拟环境中运行它吗?由于 Docker 容器通常无法访问主机文件,因此这类主要读写文件的脚本通常更容易在容器外运行。
  • 如果这不是一个选项,脚本是否知道在 /app/input 目录中查找输入文件?

标签: python docker image containers


【解决方案1】:

我认为您以错误的方式使用 ENTRYPOINT。请参阅this question 并阅读有关 ENTRYPOINT 和 CMD 的更多信息。简而言之,当您运行 docker 时,您在图像名称后指定的内容将作为 CMD 传递,意味着将作为参数列表传递给 ENTRYPOINT。请参阅下一个示例:

文件:

FROM python:3.8-slim

WORKDIR /app

COPY run.py .

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

运行.py:

import sys

print(sys.argv[1:])

当你运行它时:

> docker run -it --rm run-docker-image-with-json-file-as-variable arg1 arg2 arg3
['arg1', 'arg2', 'arg3']

> docker run -it --rm run-docker-image-with-json-file-as-variable python3 run.py arg1 arg2 arg3
['python3', 'run.py', 'arg1', 'arg2', 'arg3']

【讨论】:

    【解决方案2】:

    使用 -v $(pwd)/json_file.json:/mapped_file.json 之类的东西将 json 文件映射到容器中,并将映射的文件名传递给您的程序,这样您就可以得到

    docker run -v $(pwd)/json_file.json:/mapped_file.json -v /local/input:/app/input -v /local/output:/app/output/ -t docker_image python3 run.py model-segmentation-512.h5 /mapped_file.json
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-21
      • 2022-06-13
      • 2016-05-05
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多