我想使用远程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
并根据tar archive
传递documentation时,它失败并出现错误:
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")
好。我找到了解决方案。我不得不在.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()