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.
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.
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
.
shutils
module , I think its shipped with python, you can use it to compress.
Jul 18, 2021 at 14:39