Python Docker - 绑定源路径不存在

问题描述 投票:0回答:1

我基本上想使用 python docker 客户端在另一个 docker 容器中运行一个外部 docker 容器。基本上,将在 docker 容器内运行的 python 脚本将拉入图像,然后运行容器。我尝试先在本地运行独立的 python 脚本,但没有遇到任何问题。现在,当我尝试从 docker 容器中运行脚本时,它失败并出现以下错误:

docker.errors.APIError: 400 Client Error for http+docker://localhost/v1.41/containers/create: Bad Request ("invalid mount config for type "bind": bind source path does not exist: /code/User_Input.json")

这是我的 dockerfile:

FROM python3.7

WORKDIR /code

USER root

COPY ./requirements.txt /code/requirements.txt
RUN pip3 install -r /code/requirements.txt
COPY ./main.py /code/main.py
COPY ./config.json /code/config.json
COPY ./templates/ /code/


CMD ["python3", "main.py"]

这是我的 Python 脚本的片段:

client.images.pull(docker_image)

cwd = os.getcwd()

with open(f"{cwd}/User_Input.json", "w") as f:
    json.dump(user_input, f)

# Mount the current directory to /code/hostcwd
volumes = {cwd: {"bind": "/home/hostcwd", "mode": "rw"}}

# Mount the input json file to /User_Input.json inside the container
mounts = [
        docker.types.Mount(
            type="bind", source=f"{cwd}/User_Input.json", target="/User_Input.json", read_only=False
        )
    ]

container = client.containers.run(
        docker_image,
        command=None,
        volumes=volumes,
        environment=env_vars,
        mounts=mounts,
        stdin_open=True,
        stdout=True,
        stderr=True,
        remove=True,
        tty=True,
        detach=True,
    )

for line in container.logs(stream=True):
    print(line.decode("utf-8"), end="")

我很困惑,因为它抱怨绑定源路径不存在,但我在我的 python 脚本中手动将文件创建到该指定路径,当我 ssh 进入容器时,我看到了

User_Input.json
.

python docker volume mount
1个回答
0
投票

看起来不可能将文件从一个容器挂载到另一个容器。作为解决方法,您可以使用 docker 客户端构建新映像。您可以在新的 docker 构建中使用

COPY
命令,它将文件从容器内的源文件夹复制到新的 docker 的工作目录。这样就不用再依赖docker了
volumes
mounts
.

这里是一个实现的例子:

with open(f"./User_Input.json", "w") as f:
    json.dump(user_input, f)

dockerfile = f"""
FROM {docker_image}
COPY ./User_Input.json ./
"""

with open("Dockerfile", "w") as f:
    f.write(dockerfile)

new_image, build_logs = client.images.build(path=".", quiet=False, tag="latest")

container = client.containers.run(
        new_image,
        command=None,
        environment=env_vars,
        stdin_open=True,
        stdout=True,
        stderr=True,
        remove=True,
        tty=True,
        detach=True,
    )
© www.soinside.com 2019 - 2024. All rights reserved.