or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

containers.mdimages.mdindex.mdnetworking.mdswarm.mdutilities.md
tile.json

tessl/pypi-docker-py

A comprehensive Python client library for the Docker Remote API enabling programmatic control of containers, images, networks, and volumes.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/docker-py@1.10.x

To install, run

npx @tessl/cli install tessl/pypi-docker-py@1.10.0

index.mddocs/

Docker-Py

A 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.

Package Information

  • Package Name: docker-py
  • Language: Python
  • Installation: pip install docker-py
  • Version: 1.10.6
  • License: Apache License 2.0
  • Documentation: https://docker-py.readthedocs.io/en/latest/

Core Imports

import docker

Main client access:

from docker import Client

Alternative 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, NotFound

Basic Usage

import 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')

Architecture

Docker-py uses a modular architecture built around mixins that provide specific Docker functionality:

  • Client: Main client class inheriting from requests.Session and 9 API mixins
  • API Mixins: Specialized classes providing Docker API functionality (containers, images, networks, etc.)
  • Types: Data classes for complex Docker API objects and configurations
  • Utils: Helper functions for data conversion, configuration building, and protocol handling
  • Transport: Custom HTTP adapters for Unix sockets, Windows named pipes, and TLS connections

This design allows comprehensive Docker API coverage while maintaining code organization and extensibility.

Capabilities

Container Operations

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): ...

Container Operations

Image Management

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): ...

Image Management

Network Management

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): ...

Network Management

Volume Management

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): ...

Services and Swarm

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): ...

Services and Swarm

System Information

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 Client Classes

Client

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): ...

AutoVersionClient

Client that automatically detects and uses the appropriate Docker API version.

class AutoVersionClient(Client):
    def __init__(self, *args, **kwargs): ...  # version parameter not allowed

from_env Function

Convenience function to create a client from environment variables.

def from_env(**kwargs) -> Client:
    """Create Client instance from environment variables (DOCKER_HOST, etc.)"""

Core Type Classes

LogConfig

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"

Ulimit

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 limit

Mount

Volume 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 flag

Error Classes

class 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"""

Constants

# 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

Configuration and Utilities