1

我想使用远程 docker 主机通过 Python Docker API 从内存中的 tar 构建图像。

当只发送一个 Dockerfile 时,我已经成功创建了一个 docker 映像,如下所示:

client.images.build(fileobj=BytesIO(dockerfile_str.encode("utf-8"))
                    tag="some_image_name",
                    encoding="utf-8")

但是,当我尝试根据文档custom_context=True设置和传递 a时,它会失败并出现错误:tar archive

docker.errors.APIError: 500 Server Error: Internal Server Error ("Cannot locate specified Dockerfile: Dockerfile")

这就是我尝试这样做的方式:

with tarfile.open(fileobj=BytesIO(), mode="w") as tar:
    dockerfile_str = """
        FROM ubuntu

        ENTRYPOINT ["printf", "Given command is %s"]

        CMD ["not given"]
    """.encode("utf-8")

    dockerfile_tar_info = tarfile.TarInfo("Dockerfile")
    dockerfile_tar_info.size = len(dockerfile_str)

    tar.addfile(dockerfile_tar_info, BytesIO(dockerfile_str))

    client = docker.DockerClient("some_url")
    client.images.build(fileobj=tar.fileobj,
                        custom_context=True,
                        dockerfile="Dockerfile",
                        tag="some_image_name",
                        encoding="utf-8")
    client.close()

编辑:

如果我通过磁盘路由:

...
with tarfile.open("tmp_1.tar", mode="w") as tar:
...
client.images.build(fileobj=tarfile.open("tmp_1.tar", mode="r").fileobj,
...

相反,我收到以下错误消息:

docker.errors.APIError: 500 Server Error: Internal Server Error ("archive/tar: invalid tar header")  
4

1 回答 1

0

好。我找到了解决方案。我不得不打电话.getvalue()fileobj

with tarfile.open(fileobj=BytesIO(), mode="w") as tar:
    dockerfile_str = """
        FROM ubuntu

        ENTRYPOINT ["printf", "Given command is %s"]

        CMD ["not given"]
    """.encode("utf-8")

    dockerfile_tar_info = tarfile.TarInfo("Dockerfile")
    dockerfile_tar_info.size = len(dockerfile_str)

    tar.addfile(dockerfile_tar_info, BytesIO(dockerfile_str))

    client = docker.DockerClient("some_url")
    client.images.build(fileobj=tar.fileobj.getvalue(),
                        custom_context=True,
                        dockerfile="Dockerfile",
                        tag="some_image_name",
                        encoding="utf-8")
    client.close()
于 2018-12-12T14:10:06.427 回答