CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-docker

A Python library for the Docker Engine API.

Pending
Overview
Eval results
Files

client-management.mddocs/

Client Management

Client interfaces for connecting to Docker Engine with support for various connection methods, authentication, and configuration options.

Capabilities

High-Level DockerClient

The main client interface providing resource collections and convenient methods for Docker operations.

class DockerClient:
    def __init__(self, base_url='unix:///var/run/docker.sock', version='auto', timeout=60, tls=False, user_agent=None, credstore_env=None, use_ssh_client=False, max_pool_size=10):
        """
        Create a DockerClient instance.
        
        Args:
            base_url (str): URL to the Docker server. Examples:
                - 'unix:///var/run/docker.sock' (Unix socket)
                - 'tcp://127.0.0.1:2376' (TCP connection)
                - 'ssh://user@host' (SSH connection)
            version (str): API version to use ('auto' for auto-detection)
            timeout (int): Default timeout for API calls in seconds
            tls (bool or TLSConfig): Enable TLS. True for default TLS, TLSConfig for custom
            user_agent (str): Custom user agent for requests
            credstore_env (dict): Environment variables for credential store
            use_ssh_client (bool): Use SSH client for connections
            max_pool_size (int): Maximum connection pool size
        """

Class Methods

@classmethod
def from_env(cls, **kwargs):
    """
    Create a client configured from environment variables.
    
    Uses DOCKER_HOST, DOCKER_TLS_VERIFY, DOCKER_CERT_PATH environment variables.
    
    Returns:
        DockerClient: Configured client instance
    """

System Operations

def close(self):
    """Close the client connection and clean up resources."""

def df(self):
    """
    Get Docker system disk usage information.
    
    Returns:
        dict: Disk usage data including images, containers, volumes, build cache
    """

def info(self):
    """
    Get Docker system information.
    
    Returns:
        dict: System information including version, storage driver, kernel version
    """

def ping(self):
    """
    Ping the Docker daemon.
    
    Returns:
        bool: True if daemon is reachable
        
    Raises:
        APIError: If daemon is unreachable
    """

def version(self, api_version=True):
    """
    Get Docker version information.
    
    Args:
        api_version (bool): Include API version information
        
    Returns:
        dict: Version information including Docker version, API version, Git commit
    """

Authentication

def login(self, username, password=None, email=None, registry=None, reauth=False, **kwargs):
    """
    Authenticate with a Docker registry.
    
    Args:
        username (str): Registry username
        password (str): Registry password (prompted if None)
        email (str): Registry email (optional)
        registry (str): Registry URL (defaults to Docker Hub)
        reauth (bool): Force re-authentication
        
    Returns:
        dict: Authentication response
        
    Raises:
        APIError: If authentication fails
    """

Event Streaming

def events(self, since=None, until=None, filters=None, decode=None):
    """
    Stream Docker events from the daemon.
    
    Args:
        since (datetime or str): Show events since this time
        until (datetime or str): Show events until this time  
        filters (dict): Event filters by type, container, image, etc.
        decode (bool): Decode JSON events automatically
        
    Yields:
        dict: Event objects containing action, type, time, actor information
    """

Resource Collections

The DockerClient provides access to resource collections:

@property
def containers(self):
    """ContainerCollection: Container management operations"""

@property  
def images(self):
    """ImageCollection: Image management operations"""

@property
def networks(self):
    """NetworkCollection: Network management operations"""

@property
def volumes(self):
    """VolumeCollection: Volume management operations"""

@property
def services(self):
    """ServiceCollection: Docker Swarm service operations"""

@property
def configs(self):
    """ConfigCollection: Docker config management"""

@property
def secrets(self):
    """SecretCollection: Docker secret management"""

@property
def plugins(self):
    """PluginCollection: Plugin management operations"""

@property
def nodes(self):
    """NodeCollection: Swarm node management"""

@property
def swarm(self):
    """Swarm: Swarm cluster management"""

Low-Level APIClient

Direct Docker Engine API access for advanced use cases requiring full control.

class APIClient:
    def __init__(self, base_url='unix:///var/run/docker.sock', version='auto', timeout=60, tls=False, user_agent=None, credstore_env=None, use_ssh_client=False, max_pool_size=10):
        """
        Create an APIClient instance with the same parameters as DockerClient.
        
        This client inherits from requests.Session and provides direct access
        to Docker Engine API endpoints.
        """

    def reload_config(self, dockercfg_path=None):
        """
        Reload authentication configuration from Docker config file.
        
        Args:
            dockercfg_path (str): Path to Docker config file (optional)
        """

    @property
    def api_version(self):
        """str: Current Docker API version being used"""

    @property
    def base_url(self):
        """str: Base URL of the Docker daemon"""

    @property  
    def timeout(self):
        """int: Request timeout in seconds"""

Factory Function

def from_env(**kwargs):
    """
    Create a DockerClient configured from environment variables.
    
    Convenience function equivalent to DockerClient.from_env().
    
    Args:
        **kwargs: Additional arguments passed to DockerClient constructor
        
    Returns:
        DockerClient: Configured client instance
    """

TLS Configuration

class TLSConfig:
    def __init__(self, client_cert=None, ca_cert=None, verify=None):
        """
        TLS configuration for secure Docker connections.
        
        Args:
            client_cert (tuple): (cert_path, key_path) for client certificate
            ca_cert (str): Path to CA certificate file
            verify (bool or str): Verify server certificate. True uses ca_cert,
                                 str path uses custom CA, False disables verification
        """

    def configure_client(self, client):
        """
        Configure a requests client with TLS settings.
        
        Args:
            client: requests.Session object to configure
        """

Usage Examples

Basic Client Creation

import docker

# From environment variables (recommended)
client = docker.from_env()

# Custom connection
client = docker.DockerClient(
    base_url='tcp://192.168.1.100:2376',
    timeout=30
)

# SSH connection  
client = docker.DockerClient(
    base_url='ssh://user@remote-host',
    use_ssh_client=True
)

TLS Configuration

import docker

# Basic TLS
client = docker.DockerClient(
    base_url='tcp://192.168.1.100:2376',
    tls=True
)

# Custom TLS configuration
tls_config = docker.TLSConfig(
    client_cert=('/path/to/cert.pem', '/path/to/key.pem'),
    ca_cert='/path/to/ca.pem',
    verify=True
)

client = docker.DockerClient(
    base_url='tcp://192.168.1.100:2376',
    tls=tls_config
)

System Information

client = docker.from_env()

# System info
info = client.info()
print(f"Docker version: {info['ServerVersion']}")
print(f"Storage driver: {info['Driver']}")

# Disk usage
usage = client.df()
print(f"Images: {len(usage['Images'])} using {usage['LayersSize']} bytes")

# Version details
version = client.version()
print(f"API version: {version['ApiVersion']}")

Event Monitoring

import docker
from datetime import datetime, timedelta

client = docker.from_env()

# Monitor all events
for event in client.events(decode=True):
    print(f"{event['time']}: {event['Action']} on {event['Type']}")

# Filter events
filters = {'type': 'container', 'event': ['start', 'stop']}
since = datetime.now() - timedelta(hours=1)

for event in client.events(since=since, filters=filters, decode=True):
    container_name = event['Actor']['Attributes'].get('name', 'unknown')
    print(f"Container {container_name}: {event['Action']}")

Install with Tessl CLI

npx tessl i tessl/pypi-docker

docs

client-management.md

config-secrets.md

container-management.md

context-management.md

error-handling.md

image-management.md

index.md

network-management.md

plugin-management.md

swarm-services.md

system-events.md

volume-management.md

tile.json