A Python library for the Docker Engine API.
npx @tessl/cli install tessl/pypi-docker@7.1.0A comprehensive Python library for interacting with the Docker Engine API, enabling developers to perform all Docker operations programmatically from within Python applications. It offers both high-level client interfaces and low-level API access for managing containers, images, networks, volumes, and Docker Swarm services.
pip install dockerpip install docker[ssh] for SSH connectionspip install docker[websockets] for WebSocket attach supportimport docker
# Access version information
print(docker.__version__)Create a client:
# High-level client (recommended)
client = docker.DockerClient(base_url='unix:///var/run/docker.sock')
# Or from environment variables
client = docker.from_env()
# Low-level API client
api_client = docker.APIClient(base_url='unix:///var/run/docker.sock')import docker
# Create client from environment
client = docker.from_env()
# Pull an image
client.images.pull('hello-world')
# Run a container
container = client.containers.run(
'hello-world',
detach=True,
name='my-hello-world'
)
# Check container status
print(container.status)
# Get container logs
logs = container.logs()
print(logs.decode('utf-8'))
# Stop and remove container
container.stop()
container.remove()
# List all containers
containers = client.containers.list(all=True)
for container in containers:
print(f"{container.name}: {container.status}")
# Build image from Dockerfile
image = client.images.build(
path='/path/to/dockerfile/directory',
tag='my-custom-image:latest'
)The Docker Python library provides two main interface levels:
DockerClient): Object-oriented resource collections with convenient methodsAPIClient): Direct Docker Engine API access with full controlResource Collections manage Docker objects:
This design enables both simple scripting and complex Docker orchestration workflows.
High-level and low-level client interfaces for connecting to Docker Engine with support for various connection methods including Unix sockets, TCP, SSH tunnels, and TLS authentication.
class DockerClient:
def __init__(self, *args, **kwargs): ...
@classmethod
def from_env(cls, **kwargs): ...
def close(self): ...
def df(self): ...
def info(self): ...
def login(self, username, password=None, email=None, registry=None, reauth=False, **kwargs): ...
def ping(self): ...
def version(self, api_version=True): ...
def events(self, since=None, until=None, filters=None, decode=None): ...
def from_env(**kwargs): ...
class APIClient:
def __init__(self, base_url=None, version=None, timeout=60, tls=False, user_agent=None, num_pools=None, credstore_env=None, use_ssh_client=False, max_pool_size=10): ...
def reload_config(self, dockercfg_path=None): ...Complete container lifecycle management including creation, execution, monitoring, and resource control with support for advanced features like container attachment, file transfer, and process execution.
class ContainerCollection:
def run(self, image, command=None, **kwargs): ...
def create(self, image, command=None, **kwargs): ...
def get(self, container_id): ...
def list(self, all=False, before=None, filters=None, **kwargs): ...
def prune(self, filters=None): ...
class Container:
def start(self, **kwargs): ...
def stop(self, timeout=10): ...
def restart(self, timeout=10): ...
def kill(self, signal='SIGKILL'): ...
def pause(self): ...
def unpause(self): ...
def remove(self, v=False, link=False, force=False): ...
def exec_run(self, cmd, **kwargs): ...
def logs(self, **kwargs): ...
def stats(self, decode=None, stream=True): ...
def attach(self, **kwargs): ...
def commit(self, repository=None, tag=None, **kwargs): ...Docker image operations including building, pulling, pushing, tagging, and registry interactions with support for multi-platform builds and custom build contexts.
class ImageCollection:
def build(self, **kwargs): ...
def get(self, name): ...
def get_registry_data(self, name, auth_config=None): ...
def list(self, name=None, all=False, filters=None): ...
def load(self, data): ...
def pull(self, repository, tag=None, all_tags=False, **kwargs): ...
def push(self, repository, tag=None, **kwargs): ...
def search(self, term, **kwargs): ...
def prune(self, filters=None): ...
def prune_builds(self, **kwargs): ...
class Image:
def history(self): ...
def reload(self): ...
def remove(self, force=False, noprune=False): ...
def save(self, chunk_size=2097152): ...
def tag(self, repository, tag=None, **kwargs): ...Docker network creation, configuration, and container connectivity management with support for custom networks, network drivers, and advanced networking features.
class NetworkCollection:
def create(self, name, **kwargs): ...
def get(self, network_id): ...
def list(self, names=None, ids=None, filters=None): ...
def prune(self, filters=None): ...
class Network:
def connect(self, container, **kwargs): ...
def disconnect(self, container, **kwargs): ...
def remove(self): ...Docker volume operations for persistent data storage including volume creation, mounting, and lifecycle management with support for volume drivers and custom configurations.
class VolumeCollection:
def create(self, name=None, **kwargs): ...
def get(self, volume_id): ...
def list(self, filters=None): ...
def prune(self, filters=None): ...
class Volume:
def remove(self, force=False): ...Docker Swarm service orchestration including service creation, scaling, updating, and management with support for service constraints, placement preferences, and rolling updates.
class ServiceCollection:
def create(self, image, **kwargs): ...
def get(self, service_id): ...
def list(self, filters=None): ...
class Service:
def logs(self, **kwargs): ...
def remove(self): ...
def scale(self, replicas): ...
def update(self, **kwargs): ...Docker configuration and secret management for secure credential handling and application configuration with support for external secret stores and configuration templating.
class ConfigCollection:
def create(self, **kwargs): ...
def get(self, config_id): ...
def list(self, filters=None): ...
class SecretCollection:
def create(self, **kwargs): ...
def get(self, secret_id): ...
def list(self, filters=None): ...
class Config:
def remove(self): ...
class Secret:
def remove(self): ...Docker plugin installation, configuration, and lifecycle management with support for volume drivers, network drivers, and custom plugin development.
class PluginCollection:
def create(self, **kwargs): ...
def get(self, name): ...
def list(self, filters=None): ...
def install(self, remote_name, local_name=None): ...
class Plugin:
def configure(self, options): ...
def disable(self, **kwargs): ...
def enable(self, timeout=0): ...
def push(self, **kwargs): ...
def remove(self, **kwargs): ...
def upgrade(self, **kwargs): ...Docker daemon system information, resource usage monitoring, and real-time event streaming for comprehensive Docker environment observability.
def df(self): ...
def info(self): ...
def ping(self): ...
def version(self, api_version=True): ...
def events(self, since=None, until=None, filters=None, decode=None): ...Docker context management for connecting to different Docker hosts and orchestrators with persistent configuration and credential storage.
class Context:
def __init__(self, name, orchestrator=None, host=None, endpoints=None, tls=False): ...
def set_endpoint(self, name='docker', host=None, tls_cfg=None, skip_tls_verify=False, def_namespace=None): ...
def inspect(self): ...
def save(self): ...
def remove(self): ...
@classmethod
def load_context(cls, name): ...
class ContextAPI:
@classmethod
def create_context(cls, name, orchestrator=None, host=None, tls_cfg=None, default_namespace=None, skip_tls_verify=False): ...
@classmethod
def get_context(cls, name=None): ...
@classmethod
def list_contexts(cls): ...
@classmethod
def remove_context(cls, name): ...
@classmethod
def get_current_context_name(cls): ...Comprehensive exception hierarchy for robust error handling and debugging with specific exceptions for different failure scenarios.
class DockerException(Exception): ...
class APIError(requests.exceptions.HTTPError, DockerException): ...
class NotFound(APIError): ...
class ImageNotFound(NotFound): ...
class ContainerError(DockerException): ...
class BuildError(DockerException): ...
class TLSParameterError(DockerException): ...class TLSConfig:
def __init__(self, client_cert=None, ca_cert=None, verify=None): ...
def configure_client(self, client): ...