Image Management - docker/docker-py

Image Management with Docker and Python

This document covers image management using Docker and the Python library docker-py. It includes pulling, building, tagging, and listing images, as well as exploring image details and metadata.

Pulling Images

To pull an image from a registry, use the docker.APIClient().pull() method. For example, to pull the python image:

import docker

client = docker.from_env()
client.images.pull('python')

You can also specify a tagged image, such as python:3.9.

Building Images

To build an image from a Dockerfile, use the docker.APIClient().build() method. For example, to build an image named my-image from the current directory:

client = docker.from_env()
build_stream = client.images.build(path='.', tag='my-image')
for line in build_stream:
print(line)

You can also specify a Dockerfile other than Dockerfile by using the dockerfile parameter.

Tagging Images

To tag an image, use the docker.APIClient().tag() method. For example, to tag an image with the name my-image:v1.0.0:

client = docker.from_env()
client.images.tag('my-image', 'my-image:v1.0.0')

Listing Images

To list images, use the docker.APIClient().images() method. For example, to list all images:

client = docker.from_env()
images = client.images.list()
for image in images:
print(image)

You can also filter images by name or tag.

Exploring Image Details and Metadata

To explore image details and metadata, use the docker.Image object returned by the docker.APIClient().images() method. For example, to print the image ID, creation date, and tag of an image:

client = docker.from_env()
image = client.images.get('my-image')
print(f'Image ID: {image.id}')
print(f'Creation date: {image.attrs["Created"]}')
print(f'Tag: {image.tags[0]}')

You can also inspect the image configuration and history.

Dependencies

The following dependencies are required for image management with Docker and Python:

  • Docker
  • Python
  • Requests
  • urllib3
  • hatchling
  • hatch-vcs
  • paramiko
  • pywin32
  • websocket-client
  • Sphinx

Further Reading

For more information, see: