0

How can I save docker image locally in my system using python SDK. I know how to to export it via command line as mentioned over here.

However, I want to save the image (compressed form .tar.gz format) while running an python application.

Thanks.

1 Answer 1

0

Assuming you have already created a client and able to communicate with the daemon dockerd.

>>> import docker
>>> client = docker.DockerClient(base_url='unix://var/run/docker.sock')

You should be able to retrieve the running container by name or id:

>>> container_object = client.containers.get(name_or_id)
>>> container_image = container.image

The image object should have the method you are looking for as mentioned here: https://docker-py.readthedocs.io/en/stable/images.html#docker.models.images.Image.save

 f = open('/tmp/someimage-latest.tar', 'wb')
 for chunk in container_image.save(chunk_size=2097152, named=False):
    f.write(chunk)
 f.close()

Worth mentioning that the .save() method will return a stream of raw archive data, that's why we specify chunk_size.

5
  • Thanks Saleem, however I want to save in compressed form Jul 18, 2021 at 13:46
  • Yes, that's going to save a compressed .tar archive file Jul 18, 2021 at 13:56
  • Unless you mean something else when you say compressed Jul 18, 2021 at 13:58
  • If I do .tar.gz format, the image size almost becomes half. Hence I was more looking with respect to .tar.gz format. Thanks. Jul 18, 2021 at 14:03
  • There is a shutils module , I think its shipped with python, you can use it to compress. Jul 18, 2021 at 14:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.