【问题标题】:Create docker from tar with Python Docker API使用 Python Docker API 从 tar 创建 docker
【发布时间】:2018-12-12 13:15:27
【问题描述】:

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

当我只发送一个 Dockerfile 时,我已经成功地创建了一个 docker 镜像:

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

但是,当我尝试根据documentation 设置custom_context=True 并传递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")  

【问题讨论】:

    标签: python docker docker-api


    【解决方案1】:

    嗯。我找到了解决方案。我不得不在fileobj 上致电.getvalue()

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多