gpt4 book ai didi

python - 使用 Python Docker API 从 tar 创建 docker

转载 作者:太空宇宙 更新时间:2023-11-03 21:27:44 25 4
gpt4 key购买 nike

我想使用远程 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 并根据 documentation 传递 tar 存档 时它失败并出现错误:

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

最佳答案

嗯。我找到了解决方案。我必须在 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()

关于python - 使用 Python Docker API 从 tar 创建 docker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53743886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com