1

I want to use a remote docker host to build an image from an in memory tar with the Python Docker API.

I have successfully created a docker image when sending just a Dockerfile like so:

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

However, when I try to set custom_context=True and pass a tar archive according to the documentation it fails with the error:

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

This is how I try to do it:

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

EDIT:

If I take the route over disk with:

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

I instead get the following error message:

docker.errors.APIError: 500 Server Error: Internal Server Error ("archive/tar: invalid tar header")  
Hampus
  • 2,769
  • 1
  • 22
  • 38

1 Answers1

0

Well. I found the solution. I had to call .getvalue() on 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()
Hampus
  • 2,769
  • 1
  • 22
  • 38