A comprehensive Python client library for the Docker Remote API enabling programmatic control of containers, images, networks, and volumes.
—
Comprehensive Docker image operations including pulling from registries, building from Dockerfiles, tagging, pushing, and local management. Supports both public and private registries with authentication and provides complete image lifecycle management capabilities.
Functions for discovering and examining Docker images in the local system.
def images(name=None, quiet=False, all=False, viz=False, filters=None):
"""
List Docker images.
Parameters:
- name (str): Image name to filter by
- quiet (bool): Only return image IDs
- all (bool): Show all images (including intermediate layers)
- viz (bool): Return image tree visualization (deprecated)
- filters (dict): Filters to process on image list
Returns:
list: List of image dictionaries with metadata
"""
def inspect_image(image):
"""
Get detailed information about an image.
Parameters:
- image (str): Image name, ID, or tag
Returns:
dict: Detailed image information including config, layers, and metadata
"""
def history(image):
"""
Get the history of an image showing layer information.
Parameters:
- image (str): Image name, ID, or tag
Returns:
list: List of layer history entries
"""
def search(term):
"""
Search Docker Hub for images.
Parameters:
- term (str): Search term
Returns:
list: List of search results from Docker Hub
"""Functions for pulling images from registries and pushing local images to remote repositories.
def pull(repository, tag=None, stream=False, insecure_registry=False,
auth_config=None, decode=False):
"""
Pull an image from a registry.
Parameters:
- repository (str): Repository name (e.g., 'ubuntu', 'library/ubuntu')
- tag (str): Image tag (default: 'latest')
- stream (bool): Stream pull output as generator
- insecure_registry (bool): Allow insecure registry connections
- auth_config (dict): Authentication configuration
- decode (bool): Decode JSON stream output
Returns:
generator|bytes: Pull output stream or raw data
"""
def push(repository, tag=None, stream=False, insecure_registry=False,
auth_config=None, decode=False):
"""
Push an image to a registry.
Parameters:
- repository (str): Repository name
- tag (str): Image tag (default: 'latest')
- stream (bool): Stream push output as generator
- insecure_registry (bool): Allow insecure registry connections
- auth_config (dict): Authentication configuration
- decode (bool): Decode JSON stream output
Returns:
generator|bytes: Push output stream or raw data
"""Build Docker images from Dockerfiles or build contexts with comprehensive configuration options.
def build(path=None, tag=None, quiet=False, fileobj=None, nocache=False,
rm=False, stream=False, timeout=None, custom_context=False,
encoding=None, pull=False, forcerm=False, dockerfile=None,
container_limits=None, decode=False, buildargs=None, gzip=False):
"""
Build a Docker image from a Dockerfile or build context.
Parameters:
- path (str): Path to build context directory
- tag (str): Tag for the built image
- quiet (bool): Suppress build output
- fileobj (file): File-like object containing Dockerfile or build context
- nocache (bool): Do not use cache when building
- rm (bool): Remove intermediate containers after build
- stream (bool): Stream build output as generator
- timeout (int): Timeout for build process
- custom_context (bool): Use custom build context
- encoding (str): Encoding for build context
- pull (bool): Always pull base images
- forcerm (bool): Always remove intermediate containers
- dockerfile (str): Path to Dockerfile within build context
- container_limits (dict): Container resource limits during build
- decode (bool): Decode JSON build output
- buildargs (dict): Build-time variables
- gzip (bool): Compress build context with gzip
Returns:
generator|list: Build output stream or list of build steps
"""Local image operations including tagging, removal, and data export/import.
def tag(image, repository, tag=None, force=False):
"""
Tag an image into a repository.
Parameters:
- image (str): Image name or ID to tag
- repository (str): Repository name for the tag
- tag (str): Tag name (default: 'latest')
- force (bool): Force tag creation
Returns:
bool: Success status
"""
def remove_image(image, force=False, noprune=False):
"""
Remove an image.
Parameters:
- image (str): Image name, ID, or tag
- force (bool): Force removal of image
- noprune (bool): Do not delete untagged parents
Returns:
list: List of deleted images and untagged references
"""
def get_image(image):
"""
Get an image as a tar archive.
Parameters:
- image (str): Image name, ID, or tag
Returns:
generator: Tar archive data stream
"""
def load_image(data):
"""
Load an image from tar archive data.
Parameters:
- data (bytes|file): Tar archive data or file-like object
Returns:
generator: Load output stream
"""Functions for importing images from various sources including tarballs, URLs, and other images.
def import_image(src=None, repository=None, tag=None, image=None,
changes=None, stream_src=False):
"""
Import an image from a tarball or URL.
Parameters:
- src (str): Source URL or '-' for stdin
- repository (str): Repository name for imported image
- tag (str): Tag for imported image
- image (str): Image name (alternative to repository/tag)
- changes (list): List of Dockerfile-like changes to apply
- stream_src (bool): Treat src as stream data
Returns:
generator: Import output stream
"""
def import_image_from_data(data, repository=None, tag=None, changes=None):
"""
Import an image from raw data.
Parameters:
- data (bytes): Raw image data
- repository (str): Repository name
- tag (str): Tag name
- changes (list): Dockerfile-like changes
Returns:
generator: Import output stream
"""
def import_image_from_file(filename, repository=None, tag=None, changes=None):
"""
Import an image from a file.
Parameters:
- filename (str): Path to image file
- repository (str): Repository name
- tag (str): Tag name
- changes (list): Dockerfile-like changes
Returns:
generator: Import output stream
"""
def import_image_from_stream(stream, repository=None, tag=None, changes=None):
"""
Import an image from a stream.
Parameters:
- stream (file): File-like stream object
- repository (str): Repository name
- tag (str): Tag name
- changes (list): Dockerfile-like changes
Returns:
generator: Import output stream
"""
def import_image_from_url(url, repository=None, tag=None, changes=None):
"""
Import an image from a URL.
Parameters:
- url (str): URL to import from
- repository (str): Repository name
- tag (str): Tag name
- changes (list): Dockerfile-like changes
Returns:
generator: Import output stream
"""
def import_image_from_image(image, repository=None, tag=None, changes=None):
"""
Import from an existing image.
Parameters:
- image (str): Source image name or ID
- repository (str): Repository name
- tag (str): Tag name
- changes (list): Dockerfile-like changes
Returns:
generator: Import output stream
"""Legacy image operations maintained for backwards compatibility.
def insert(image, url, path):
"""
Insert a file into an image (deprecated for API < 1.12).
Parameters:
- image (str): Image name or ID
- url (str): URL to file to insert
- path (str): Path to insert file at
Returns:
dict: New image information
"""Docker registry authentication is configured using auth_config dictionaries:
# Auth config structure
auth_config = {
'username': 'your_username',
'password': 'your_password',
'email': 'your_email@example.com', # Optional
'serveraddress': 'https://index.docker.io/v1/', # Registry URL
'auth': 'base64_encoded_credentials' # Alternative to username/password
}import docker
client = docker.Client()
# Pull an image
for line in client.pull('ubuntu:20.04', stream=True, decode=True):
print(line.get('status', ''))
# List all images
images = client.images()
for image in images:
print(f"Repository: {image['RepoTags']}, Size: {image['Size']}")
# Inspect an image
image_info = client.inspect_image('ubuntu:20.04')
print(f"Architecture: {image_info['Architecture']}")
print(f"OS: {image_info['Os']}")
# Tag an image
client.tag('ubuntu:20.04', 'my-ubuntu', 'latest')
# Remove an image
client.remove_image('my-ubuntu:latest')# Build from Dockerfile in current directory
for line in client.build(path='.', tag='my-app:latest', stream=True, decode=True):
if 'stream' in line:
print(line['stream'].strip())
# Build with custom Dockerfile and build arguments
build_output = client.build(
path='/path/to/build/context',
dockerfile='Dockerfile.prod',
tag='my-app:production',
buildargs={
'BUILD_ENV': 'production',
'VERSION': '1.2.3'
},
pull=True,
nocache=True,
rm=True,
stream=True,
decode=True
)
for line in build_output:
if 'stream' in line:
print(line['stream'].strip())# Configure authentication
auth_config = {
'username': 'myuser',
'password': 'mypassword',
'serveraddress': 'registry.example.com'
}
# Pull from private registry
client.pull(
'registry.example.com/my-private-repo:latest',
auth_config=auth_config,
stream=True
)
# Push to private registry
client.tag('my-app:latest', 'registry.example.com/my-private-repo:v1.0')
for line in client.push(
'registry.example.com/my-private-repo:v1.0',
auth_config=auth_config,
stream=True,
decode=True
):
print(line.get('status', ''))# Export image to tar file
with open('my-image.tar', 'wb') as f:
for chunk in client.get_image('my-app:latest'):
f.write(chunk)
# Load image from tar file
with open('my-image.tar', 'rb') as f:
client.load_image(f)
# Import image from tarball with modifications
changes = [
'ENV NEW_VAR=value',
'EXPOSE 8080'
]
client.import_image_from_file(
'exported-container.tar',
repository='imported-app',
tag='latest',
changes=changes
)# Build with resource limits
container_limits = {
'memory': 1024 * 1024 * 512, # 512MB
'memswap': 1024 * 1024 * 1024, # 1GB
'cpushares': 512,
'cpusetcpus': '0,1'
}
for line in client.build(
path='/build/context',
tag='resource-limited:latest',
container_limits=container_limits,
pull=True,
forcerm=True,
stream=True,
decode=True
):
if 'stream' in line:
print(line['stream'].strip())# Search Docker Hub
search_results = client.search('nginx')
for result in search_results[:5]: # Show top 5 results
print(f"Name: {result['name']}")
print(f"Description: {result['description']}")
print(f"Stars: {result['star_count']}")
print(f"Official: {result['is_official']}")
print("---")
# Get image history
history = client.history('nginx:latest')
for layer in history:
print(f"Created: {layer['Created']}")
print(f"Size: {layer['Size']}")
print(f"Created by: {layer['CreatedBy'][:50]}...")
print("---")Install with Tessl CLI
npx tessl i tessl/pypi-docker-py