CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-python-on-whales

A Docker client for Python, designed to be fun and intuitive!

Pending
Overview
Eval results
Files

client.mddocs/

Client Configuration

Main Docker client interface and configuration options for connecting to different Docker daemons, setting up contexts, and managing authentication. The DockerClient serves as the primary entry point for all Docker operations.

Capabilities

Client Initialization

Create and configure Docker client instances with various connection options.

class DockerClient:
    def __init__(
        self,
        *,
        config: Optional[str] = None,
        context: Optional[str] = None,
        debug: bool = False,
        host: Optional[str] = None,
        log_level: str = "info",
        tls: bool = False,
        tlscacert: Optional[str] = None,
        tlscert: Optional[str] = None,
        tlskey: Optional[str] = None,
        tlsverify: bool = False,
        compose_files: Optional[List[str]] = None,
        compose_profiles: Optional[List[str]] = None,
        compose_env_file: Optional[str] = None,
        compose_project_name: Optional[str] = None,
        compose_project_directory: Optional[str] = None,
        compose_compatibility: bool = False,
        client_call: Optional[List[str]] = None,
        client_type: str = "docker"
    ):
        """
        Initialize Docker client.
        
        Parameters:
        - config: Location of client config files (default "~/.docker")
        - context: Name of the context to use for daemon connection
        - debug: Enable debug mode
        - host: Daemon socket(s) to connect to
        - log_level: Logging level (debug, info, warn, error, fatal)
        - tls: Use TLS; implied by tlsverify
        - tlscacert: Trust certs signed only by this CA
        - tlscert: Path to TLS certificate file
        - tlskey: Path to TLS key file
        - tlsverify: Use TLS and verify the remote
        - compose_files: Docker compose yaml file(s)
        - compose_profiles: List of compose profiles to use
        - compose_env_file: .env file for compose environment variables
        - compose_project_name: Name of the compose project
        - compose_project_directory: Working directory for compose
        - compose_compatibility: Use docker compose in compatibility mode
        - client_call: Client binary and arguments to use
        - client_type: Type of client (docker, podman)
        """

Version Information

Retrieve Docker client and server version information.

def version() -> Version:
    """
    Get Docker version information.
    
    Returns:
    - Version object with client and server details
    """

Authentication

Manage registry authentication and login credentials.

def login(
    server: Optional[str] = None,
    *,
    username: Optional[str] = None,
    password: Optional[str] = None,
    password_stdin: bool = False
) -> None:
    """
    Log in to Docker registry.
    
    Parameters:
    - server: Server URL (defaults to Docker Hub)
    - username: Username for authentication
    - password: Password for authentication
    - password_stdin: Read password from stdin
    """

def logout(server: Optional[str] = None) -> None:
    """
    Log out from Docker registry.
    
    Parameters:
    - server: Server URL (defaults to Docker Hub)
    """

def login_ecr(
    region: str,
    *,
    profile: Optional[str] = None,
    access_key_id: Optional[str] = None,
    secret_access_key: Optional[str] = None,
    session_token: Optional[str] = None
) -> None:
    """
    Log in to Amazon ECR.
    
    Parameters:
    - region: AWS region
    - profile: AWS profile to use
    - access_key_id: AWS access key ID
    - secret_access_key: AWS secret access key
    - session_token: AWS session token
    """

Usage Examples

Basic Client Setup

from python_on_whales import DockerClient

# Use default Docker daemon
docker = DockerClient()

# Connect to remote Docker daemon
remote_docker = DockerClient(host="tcp://192.168.1.100:2376")

# Use specific context
context_docker = DockerClient(context="production")

# Enable debug logging
debug_docker = DockerClient(debug=True, log_level="debug")

TLS Configuration

# TLS with certificate verification
secure_docker = DockerClient(
    host="tcp://docker.example.com:2376",
    tls=True,
    tlsverify=True,
    tlscacert="/path/to/ca.pem",
    tlscert="/path/to/cert.pem",
    tlskey="/path/to/key.pem"
)

# Simple TLS without verification
simple_tls_docker = DockerClient(
    host="tcp://docker.example.com:2376",
    tls=True
)

Alternative Client Binaries

# Use Podman instead of Docker
podman = DockerClient(
    client_call=["podman"],
    client_type="podman"
)

# Use Docker with sudo
sudo_docker = DockerClient(
    client_call=["sudo", "docker"]
)

# Use nerdctl with custom options
nerdctl = DockerClient(
    client_call=["nerdctl", "--snapshotter=stargz"],
    client_type="docker"
)

# SSH to remote Docker
ssh_docker = DockerClient(
    host="ssh://user@remote-host"
)

Compose Integration

# Client with Compose configuration
compose_docker = DockerClient(
    compose_files=["docker-compose.yml", "docker-compose.prod.yml"],
    compose_project_name="myapp",
    compose_profiles=["web", "db"],
    compose_env_file=".env.production"
)

# Use the compose functionality
compose_docker.compose.up(detach=True)

Version and Authentication

# Check version compatibility
version_info = docker.version()
print(f"Client Version: {version_info.client.version}")
print(f"Server Version: {version_info.server.version}")
print(f"API Version: {version_info.client.api_version}")

# Authenticate with registry
docker.login("registry.example.com", username="myuser", password="mypass")

# Authenticate with AWS ECR
docker.login_ecr("us-west-2", profile="production")

# Logout
docker.logout("registry.example.com")

Global Docker Instance

# Use the pre-configured global instance
from python_on_whales import docker

# This is equivalent to DockerClient()
containers = docker.ps()
images = docker.images()

# All methods available on the global instance
result = docker.run("hello-world")

Configuration Validation

def validate_docker_config(client: DockerClient) -> bool:
    """Validate Docker client configuration."""
    try:
        # Test basic connectivity
        version = client.version()
        print(f"✓ Connected to Docker {version.server.version}")
        
        # Test basic operations
        client.ps()
        print("✓ Container operations available")
        
        client.images()
        print("✓ Image operations available")
        
        return True
        
    except Exception as e:
        print(f"✗ Docker configuration error: {e}")
        return False

# Test different configurations
configs = [
    DockerClient(),  # Default
    DockerClient(host="unix:///var/run/docker.sock"),  # Unix socket
    DockerClient(context="default"),  # Named context
]

for i, config in enumerate(configs):
    print(f"Testing configuration {i+1}:")
    if validate_docker_config(config):
        print("Configuration is valid\n")
    else:
        print("Configuration failed\n")

Types

class DockerClient:
    # Component access properties
    buildx: BuildxCLI
    compose: ComposeCLI
    config: ConfigCLI
    container: ContainerCLI
    context: ContextCLI
    image: ImageCLI
    manifest: ManifestCLI
    network: NetworkCLI
    node: NodeCLI
    plugin: PluginCLI
    pod: PodCLI
    secret: SecretCLI
    service: ServiceCLI
    stack: StackCLI
    swarm: SwarmCLI
    system: SystemCLI
    task: TaskCLI
    trust: TrustCLI
    volume: VolumeCLI
    
    # Direct method aliases
    def attach(self, container: str, **kwargs) -> None: ...
    def build(self, context_path: str, **kwargs) -> Image: ...
    def commit(self, container: str, **kwargs) -> Image: ...
    def copy(self, source: str, destination: str, **kwargs) -> None: ...
    def create(self, image: str, **kwargs) -> Container: ...
    def execute(self, container: str, command: List[str], **kwargs) -> str: ...
    def export(self, container: str, output_path: str) -> None: ...
    def images(self, **kwargs) -> List[Image]: ...
    def import_(self, source: str, **kwargs) -> Image: ...
    def info(self) -> SystemInfo: ...
    def kill(self, containers: Union[str, List[str]], **kwargs) -> None: ...
    def load(self, input_path: str, **kwargs) -> List[str]: ...
    def logs(self, container: str, **kwargs) -> str: ...
    def pause(self, containers: Union[str, List[str]]) -> None: ...
    def ps(self, **kwargs) -> List[Container]: ...
    def pull(self, image_name: str, **kwargs) -> Image: ...
    def push(self, image_name: str, **kwargs) -> str: ...
    def rename(self, container: str, new_name: str) -> None: ...
    def restart(self, containers: Union[str, List[str]], **kwargs) -> None: ...
    def remove(self, containers: Union[str, List[str]], **kwargs) -> None: ...
    def run(self, image: str, **kwargs) -> Union[str, Container]: ...
    def save(self, images: Union[str, List[str]], output_path: str) -> None: ...
    def start(self, containers: Union[str, List[str]]) -> None: ...
    def stats(self, **kwargs) -> Union[List[ContainerStats], Iterator[List[ContainerStats]]]: ...
    def stop(self, containers: Union[str, List[str]], **kwargs) -> None: ...
    def tag(self, source_image: str, target_repository: str, target_tag: Optional[str] = None) -> None: ...
    def top(self, container: str, **kwargs) -> List[Dict[str, str]]: ...
    def unpause(self, containers: Union[str, List[str]]) -> None: ...
    def update(self, containers: Union[str, List[str]], **kwargs) -> None: ...
    def wait(self, containers: Union[str, List[str]], **kwargs) -> List[Dict[str, Any]]: ...

class Version:
    client: Optional[ClientVersion]
    server: Optional[ServerVersion]

class ClientVersion:
    platform: Optional[Dict[str, str]]
    version: Optional[str]
    api_version: Optional[str]
    default_api_version: Optional[str]
    git_commit: Optional[str]
    go_version: Optional[str]
    os: Optional[str]
    arch: Optional[str]
    build_time: Optional[str]
    context: Optional[str]
    experimental: Optional[bool]

class ServerVersion:
    platform: Optional[Dict[str, str]]
    components: Optional[List[ServerVersionComponent]]
    version: Optional[str]
    api_version: Optional[str]
    min_api_version: Optional[str]
    git_commit: Optional[str]
    go_version: Optional[str]
    os: Optional[str]
    arch: Optional[str]
    kernel_version: Optional[str]
    build_time: Optional[str]

class ServerVersionComponent:
    name: Optional[str]
    version: Optional[str]
    details: Optional[Dict[str, str]]

Install with Tessl CLI

npx tessl i tessl/pypi-python-on-whales

docs

build.md

client.md

compose.md

config.md

containers.md

context.md

images.md

index.md

manifest.md

networks.md

node.md

plugin.md

pod.md

secret.md

service.md

stack.md

swarm.md

system.md

task.md

trust.md

volumes.md

tile.json