A comprehensive Python client library for the Docker Remote API enabling programmatic control of containers, images, networks, and volumes.
npx @tessl/cli install tessl/pypi-docker-py@1.10.0A comprehensive Python client library for the Docker Remote API. It provides complete programmatic control over Docker containers, images, networks, volumes, and services from within Python applications, enabling developers to manage Docker infrastructure through Python code rather than command-line tools.
pip install docker-pyimport dockerMain client access:
from docker import ClientAlternative import methods:
# Import client classes directly
from docker import Client, AutoVersionClient, from_env
# Import specific functionality
from docker.types import LogConfig, Ulimit, Mount
from docker.errors import APIError, NotFoundimport docker
# Create client using default settings
client = docker.Client()
# Or create client from environment variables
client = docker.from_env()
# Pull an image
client.pull('ubuntu:latest')
# Create and start a container
container = client.create_container(
image='ubuntu:latest',
command='/bin/bash',
tty=True,
detach=True,
name='my-container'
)
client.start(container)
# List running containers
containers = client.containers()
print(f"Running containers: {len(containers)}")
# Get container logs
logs = client.logs(container)
print(logs.decode('utf-8'))
# Stop and remove container
client.stop(container)
client.remove_container(container)
# List and remove images
images = client.images()
client.remove_image('ubuntu:latest')Docker-py uses a modular architecture built around mixins that provide specific Docker functionality:
requests.Session and 9 API mixinsThis design allows comprehensive Docker API coverage while maintaining code organization and extensibility.
Complete container lifecycle management including creation, startup, monitoring, and cleanup. Supports advanced features like resource constraints, networking configuration, volume mounts, and process execution within containers.
def create_container(image, command=None, **kwargs): ...
def start(container, **kwargs): ...
def stop(container, timeout=10): ...
def remove_container(container, v=False, link=False, force=False): ...
def containers(quiet=False, all=False, **kwargs): ...
def inspect_container(container): ...
def logs(container, stdout=True, stderr=True, **kwargs): ...
def exec_create(container, cmd, **kwargs): ...
def exec_start(exec_id, **kwargs): ...Image lifecycle operations including pulling from registries, building from Dockerfiles, tagging, pushing, and local management. Supports both public and private registries with authentication.
def images(name=None, quiet=False, all=False, **kwargs): ...
def pull(repository, tag=None, **kwargs): ...
def push(repository, tag=None, **kwargs): ...
def build(path=None, tag=None, **kwargs): ...
def remove_image(image, force=False, noprune=False): ...
def inspect_image(image): ...
def tag(image, repository, tag=None, force=False): ...Docker network operations for creating custom networks, connecting containers, and managing network isolation. Supports bridge, overlay, and custom network drivers with advanced configuration options.
def networks(names=None, ids=None): ...
def create_network(name, driver=None, **kwargs): ...
def remove_network(net_id): ...
def inspect_network(net_id): ...
def connect_container_to_network(container, net_id, **kwargs): ...
def disconnect_container_from_network(container, net_id, **kwargs): ...Docker volume operations for persistent data storage and sharing between containers. Supports named volumes, bind mounts, and volume driver configuration.
def volumes(filters=None): ...
def create_volume(name, driver=None, **kwargs): ...
def inspect_volume(name): ...
def remove_volume(name): ...Docker Swarm cluster management and service orchestration capabilities. Provides container orchestration, service scaling, rolling updates, and cluster administration.
def init_swarm(advertise_addr=None, **kwargs): ...
def join_swarm(remote_addrs, join_token, **kwargs): ...
def services(filters=None): ...
def create_service(task_template, name=None, **kwargs): ...
def update_service(service, version, **kwargs): ...
def nodes(filters=None): ...Docker daemon information, version details, system events, and authentication with registries.
def info(): ...
def version(api_version=True): ...
def ping(): ...
def events(since=None, until=None, **kwargs): ...
def login(username, password=None, **kwargs): ...Main Docker API client providing complete functionality through inherited mixins.
class Client(requests.Session, *ApiMixins):
def __init__(self, base_url=None, version=None, timeout=60,
tls=False, user_agent=None, num_pools=25): ...
@classmethod
def from_env(cls, **kwargs): ...
@property
def api_version(self): ...Client that automatically detects and uses the appropriate Docker API version.
class AutoVersionClient(Client):
def __init__(self, *args, **kwargs): ... # version parameter not allowedConvenience function to create a client from environment variables.
def from_env(**kwargs) -> Client:
"""Create Client instance from environment variables (DOCKER_HOST, etc.)"""Container logging configuration with support for various log drivers.
class LogConfig:
def __init__(self, **kwargs): ...
def set_config_value(self, key, value): ...
def unset_config(self, key): ...
# Properties
type: str # Log driver type
config: dict # Driver-specific configuration
# Log driver types
class LogConfigTypesEnum:
JSON = "json-file"
SYSLOG = "syslog"
JOURNALD = "journald"
GELF = "gelf"
FLUENTD = "fluentd"
NONE = "none"Process resource limits for containers.
class Ulimit:
def __init__(self, **kwargs): ...
# Properties
name: str # Resource name (e.g., 'nofile', 'nproc')
soft: int # Soft limit
hard: int # Hard limitVolume mount specification for services and containers.
class Mount:
def __init__(self, target, source, type='volume',
read_only=False, **kwargs): ...
@classmethod
def parse_mount_string(cls, string): ...
# Properties
target: str # Mount path in container
source: str # Source path or volume name
type: str # Mount type ('volume', 'bind', 'tmpfs')
read_only: bool # Read-only flagclass DockerException(Exception):
"""Base Docker exception"""
class APIError(requests.exceptions.HTTPError):
"""HTTP API error with Docker-specific details"""
def __init__(self, message, response=None, explanation=None): ...
def is_client_error(self) -> bool: ...
def is_server_error(self) -> bool: ...
class NotFound(APIError):
"""404 Not Found error"""
class InvalidVersion(DockerException):
"""Invalid API version error"""
class TLSParameterError(DockerException):
"""TLS configuration error"""# API Configuration
DEFAULT_DOCKER_API_VERSION = "1.24"
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_USER_AGENT = "docker-py/{version}"
DEFAULT_NUM_POOLS = 25
# Protocol
STREAM_HEADER_SIZE_BYTES = 8
IS_WINDOWS_PLATFORM = ... # Platform detection boolean