A Python library for the Docker Engine API.
—
Docker image operations including building, pulling, pushing, tagging, and registry interactions with support for multi-platform builds and custom build contexts.
High-level image management operations accessible via client.images.
class ImageCollection:
def build(self, **kwargs):
"""
Build an image from a Dockerfile.
Args:
**kwargs: Build configuration options
Returns:
tuple: (Image, build_logs_generator)
Common kwargs:
path (str): Path to build context directory
fileobj (file-like): File-like object containing build context tar
dockerfile (str): Path to Dockerfile relative to build context
tag (str): Tag for the built image
quiet (bool): Suppress build output
nocache (bool): Do not use cache when building
rm (bool): Remove intermediate containers (default: True)
timeout (int): Build timeout in seconds
custom_context (bool): Use custom build context
encoding (str): Encoding for build context
pull (bool): Always pull newer version of base image
forcerm (bool): Always remove intermediate containers
buildargs (dict): Build-time variables
container_limits (dict): Resource limits during build
shmsize (int): Shared memory size for build containers
labels (dict): Labels to apply to built image
cache_from (list): Images to use for build cache
target (str): Build target stage in multi-stage Dockerfile
network_mode (str): Network mode for build
squash (bool): Squash layers into single layer
extra_hosts (dict): Extra hosts for build
platform (str): Target platform for build
isolation (str): Container isolation technology
"""
def get(self, name):
"""
Get an image by name or ID.
Args:
name (str): Image name, ID, or tag
Returns:
Image: Image instance
Raises:
ImageNotFound: If image doesn't exist
"""
def get_registry_data(self, name, auth_config=None):
"""
Get image metadata from registry without pulling.
Args:
name (str): Image name with optional tag
auth_config (dict): Registry authentication config
Returns:
RegistryData: Registry metadata including digest, platform info
"""
def list(self, name=None, all=False, filters=None):
"""
List images.
Args:
name (str): Filter by image name
all (bool): Include intermediate images
filters (dict): Filter results by dangling, label, etc.
Returns:
list[Image]: List of image instances
"""
def load(self, data):
"""
Load image from tar archive.
Args:
data (bytes or file-like): Tar archive containing image
Returns:
list[Image]: Loaded images
"""
def pull(self, repository, tag=None, all_tags=False, **kwargs):
"""
Pull an image from registry.
Args:
repository (str): Repository name
tag (str): Specific tag to pull (default: latest)
all_tags (bool): Pull all tags of repository
**kwargs: Additional pull options
Returns:
Image or list[Image]: Pulled image(s)
Common kwargs:
auth_config (dict): Registry authentication
platform (str): Target platform
stream (bool): Stream pull progress
"""
def push(self, repository, tag=None, **kwargs):
"""
Push an image to registry.
Args:
repository (str): Repository name to push to
tag (str): Tag to push (default: latest)
**kwargs: Push options
Returns:
str: Push progress information
Common kwargs:
auth_config (dict): Registry authentication
stream (bool): Stream push progress
"""
def search(self, term, limit=25):
"""
Search Docker Hub for images.
Args:
term (str): Search term
limit (int): Maximum results to return
Returns:
list[dict]: Search results with name, description, stars, official status
"""
def prune(self, filters=None):
"""
Remove unused images.
Args:
filters (dict): Filters for pruning (dangling, until, label)
Returns:
dict: Pruning results with space reclaimed
"""
def prune_builds(self, **kwargs):
"""
Remove build cache.
Args:
**kwargs: Pruning options
Returns:
dict: Pruning results
Common kwargs:
filters (dict): Build cache filters
keep_storage (int): Keep specified amount of storage
all (bool): Remove all cache, not just dangling
"""Individual image instance with metadata and operations.
class Image:
"""
A Docker image instance.
Properties:
id (str): Full image ID
short_id (str): Short image ID (12 characters)
tags (list): List of image tags
labels (dict): Image labels
attrs (dict): Raw image attributes from Docker API
"""
def history(self):
"""
Get image layer history.
Returns:
list[dict]: Layer history with creation info, size, created by command
"""
def reload(self):
"""Refresh image data from Docker daemon."""
def remove(self, force=False, noprune=False):
"""
Remove the image.
Args:
force (bool): Force removal even if containers use image
noprune (bool): Do not delete untagged parent images
Returns:
list[dict]: Removal results
"""
def save(self, chunk_size=2097152):
"""
Save image as tar archive.
Args:
chunk_size (int): Chunk size for streaming
Yields:
bytes: Tar archive data chunks
"""
def tag(self, repository, tag=None, **kwargs):
"""
Tag the image.
Args:
repository (str): Repository name
tag (str): Tag name (default: latest)
**kwargs: Additional tagging options
Returns:
bool: True if successful
"""import docker
import io
client = docker.from_env()
# Build from Dockerfile in directory
image, build_logs = client.images.build(
path='/path/to/build/context',
tag='my-app:latest',
dockerfile='Dockerfile'
)
# Print build logs
for log in build_logs:
if 'stream' in log:
print(log['stream'].strip())
# Build with custom context
dockerfile_content = '''
FROM python:3.9-slim
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
'''
# Create build context in memory
import tarfile
context = io.BytesIO()
with tarfile.open(fileobj=context, mode='w') as tar:
# Add Dockerfile
dockerfile_info = tarfile.TarInfo('Dockerfile')
dockerfile_info.size = len(dockerfile_content)
tar.addfile(dockerfile_info, io.BytesIO(dockerfile_content.encode()))
# Add application files
tar.add('/local/app.py', arcname='app.py')
tar.add('/local/requirements.txt', arcname='requirements.txt')
context.seek(0)
image, logs = client.images.build(
fileobj=context,
custom_context=True,
tag='python-app:latest',
buildargs={'VERSION': '1.0'}
)# Multi-stage build with target
image, logs = client.images.build(
path='/app/source',
tag='my-app:production',
target='production',
buildargs={
'BUILD_ENV': 'production',
'VERSION': '2.1.0'
},
labels={
'version': '2.1.0',
'maintainer': 'devops@company.com'
},
cache_from=['my-app:base', 'my-app:builder'],
network_mode='host',
platform='linux/amd64',
extra_hosts={'api.internal': '192.168.1.100'}
)
# Build with resource limits
image, logs = client.images.build(
path='/app/source',
tag='memory-intensive:latest',
container_limits={
'memory': 1073741824, # 1GB
'memswap': -1,
'cpushares': 512
},
shmsize=268435456 # 256MB
)# Pull specific image
image = client.images.pull('nginx:1.21-alpine')
print(f"Pulled image: {image.tags}")
# Pull with authentication
auth_config = {
'username': 'myuser',
'password': 'mypass',
'registry': 'private-registry.com'
}
image = client.images.pull(
'private-registry.com/my-app:latest',
auth_config=auth_config
)
# Pull all tags of repository
images = client.images.pull('alpine', all_tags=True)
for img in images:
print(f"Tags: {img.tags}")
# Get registry data without pulling
registry_data = client.images.get_registry_data(
'ubuntu:20.04',
auth_config=auth_config
)
print(f"Digest: {registry_data.id}")
print(f"Platform: {registry_data.attrs['platform']}")# List and filter images
all_images = client.images.list()
for image in all_images:
print(f"ID: {image.short_id}, Tags: {image.tags}")
# Filter images
python_images = client.images.list(filters={'reference': 'python:*'})
dangling_images = client.images.list(filters={'dangling': True})
# Get specific image
image = client.images.get('nginx:latest')
print(f"Image ID: {image.id}")
print(f"Labels: {image.labels}")
# Image operations
image.tag('my-nginx:backup')
image.tag('registry.example.com/nginx:latest')
# Get image history
history = image.history()
for layer in history:
print(f"Layer: {layer['Id'][:12]}, Size: {layer['Size']}, Created: {layer['Created']}")
# Save image to file
with open('/tmp/nginx_backup.tar', 'wb') as f:
for chunk in image.save():
f.write(chunk)# Remove specific image
try:
client.images.get('old-image:latest').remove(force=True)
print("Image removed successfully")
except docker.errors.ImageNotFound:
print("Image not found")
# Prune unused images
pruned = client.images.prune()
print(f"Removed {len(pruned['ImagesDeleted'])} images")
print(f"Space reclaimed: {pruned['SpaceReclaimed']} bytes")
# Prune with filters
pruned = client.images.prune(filters={
'until': '72h', # Remove images older than 72 hours
'label': 'temporary=true'
})
# Clean build cache
cache_pruned = client.images.prune_builds()
print(f"Build cache reclaimed: {cache_pruned['SpaceReclaimed']} bytes")
# Remove all build cache
cache_pruned = client.images.prune_builds(all=True)# Load images from tar file
with open('/tmp/images_backup.tar', 'rb') as f:
loaded_images = client.images.load(f.read())
for image in loaded_images:
print(f"Loaded: {image.tags}")
# Search Docker Hub
search_results = client.images.search('python', limit=10)
for result in search_results:
print(f"Name: {result['name']}")
print(f"Description: {result['description']}")
print(f"Stars: {result['star_count']}")
print(f"Official: {result['is_official']}")
print("---")
# Push to registry
auth_config = {
'username': 'myuser',
'password': 'mytoken',
'registry': 'docker.io'
}
# Tag for registry
image = client.images.get('my-app:latest')
image.tag('myuser/my-app:v1.0')
# Push with progress
push_logs = client.images.push(
'myuser/my-app:v1.0',
auth_config=auth_config,
stream=True
)
for log in push_logs:
if 'status' in log:
print(f"{log['status']}: {log.get('progress', '')}")