CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-docker-py

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

Pending
Overview
Eval results
Files

containers.mddocs/

Container Operations

Complete container lifecycle management providing programmatic control over Docker containers. Covers creation, startup, monitoring, resource management, and cleanup operations with support for advanced features like networking, volume mounts, and process execution.

Capabilities

Container Lifecycle Management

Core container operations for creating, starting, stopping, and removing containers with comprehensive configuration options.

def create_container(image, command=None, hostname=None, user=None, 
                    detach=False, stdin_open=False, tty=False, 
                    mem_limit=None, ports=None, environment=None, 
                    dns=None, volumes=None, volumes_from=None, 
                    network_disabled=False, name=None, entrypoint=None, 
                    cpu_shares=None, working_dir=None, domainname=None, 
                    memswap_limit=None, cpuset=None, host_config=None, 
                    mac_address=None, labels=None, volume_driver=None, 
                    stop_signal=None, networking_config=None):
    """
    Create a new container.
    
    Parameters:
    - image (str): Image name to create container from
    - command (str|list): Command to run in container
    - hostname (str): Container hostname
    - user (str): Username or UID to run commands as
    - detach (bool): Run container in detached mode
    - stdin_open (bool): Keep STDIN open
    - tty (bool): Allocate a pseudo-TTY
    - mem_limit (int|str): Memory limit
    - ports (list): Ports to expose
    - environment (dict|list): Environment variables
    - dns (list): DNS servers
    - volumes (list): Volume mount points
    - volumes_from (list): Mount volumes from other containers
    - network_disabled (bool): Disable networking
    - name (str): Container name
    - entrypoint (str|list): Override default entrypoint
    - cpu_shares (int): CPU shares weight
    - working_dir (str): Working directory
    - domainname (str): Container domain name
    - memswap_limit (int): Memory + swap limit
    - cpuset (str): CPUs to use
    - host_config (dict): Host configuration
    - mac_address (str): Container MAC address
    - labels (dict): Container labels
    - volume_driver (str): Volume driver name
    - stop_signal (str): Signal to stop container
    - networking_config (dict): Network configuration
    
    Returns:
    dict: Container creation response with 'Id' key
    """

def start(container, binds=None, port_bindings=None, lxc_conf=None, 
          publish_all_ports=None, links=None, privileged=None, 
          dns=None, dns_search=None, volumes_from=None, 
          network_mode=None, restart_policy=None, cap_add=None, 
          cap_drop=None, devices=None, extra_hosts=None, 
          read_only=None, pid_mode=None, ipc_mode=None, 
          security_opt=None, ulimits=None):
    """
    Start a container.
    
    Parameters:
    - container (str): Container ID or name
    - binds (dict): Volume bindings
    - port_bindings (dict): Port bindings
    - lxc_conf (dict): LXC configuration
    - publish_all_ports (bool): Publish all exposed ports
    - links (list): Container links
    - privileged (bool): Run in privileged mode
    - dns (list): DNS servers
    - dns_search (list): DNS search domains
    - volumes_from (list): Mount volumes from containers
    - network_mode (str): Network mode
    - restart_policy (dict): Restart policy configuration
    - cap_add (list): Linux capabilities to add
    - cap_drop (list): Linux capabilities to drop
    - devices (list): Device mappings
    - extra_hosts (list): Extra host entries
    - read_only (bool): Mount root filesystem as read-only
    - pid_mode (str): PID namespace mode
    - ipc_mode (str): IPC namespace mode
    - security_opt (list): Security options
    - ulimits (list): Resource limits
    
    Returns:
    None
    """

def stop(container, timeout=10):
    """
    Stop a running container.
    
    Parameters:
    - container (str): Container ID or name
    - timeout (int): Seconds to wait before killing
    
    Returns:
    None
    """

def restart(container, timeout=10):
    """
    Restart a container.
    
    Parameters:
    - container (str): Container ID or name
    - timeout (int): Seconds to wait before killing
    
    Returns:
    None
    """

def kill(container, signal=None):
    """
    Kill a running container.
    
    Parameters:
    - container (str): Container ID or name  
    - signal (str): Signal to send (default: SIGKILL)
    
    Returns:
    None
    """

def pause(container):
    """
    Pause all processes in a container.
    
    Parameters:
    - container (str): Container ID or name
    
    Returns:
    None
    """

def unpause(container):
    """
    Unpause all processes in a container.
    
    Parameters:
    - container (str): Container ID or name
    
    Returns:
    None
    """

def remove_container(container, v=False, link=False, force=False):
    """
    Remove a container.
    
    Parameters:
    - container (str): Container ID or name
    - v (bool): Remove associated volumes
    - link (bool): Remove specified link
    - force (bool): Force removal of running container
    
    Returns:
    None
    """

def rename(container, name):
    """
    Rename a container.
    
    Parameters:
    - container (str): Container ID or name
    - name (str): New container name
    
    Returns:
    None
    """

Container Inspection and Monitoring

Functions to retrieve container information, status, and resource usage statistics.

def containers(quiet=False, all=False, trunc=False, latest=False, 
               since=None, before=None, limit=-1, size=False, filters=None):
    """
    List containers.
    
    Parameters:
    - quiet (bool): Only return container IDs
    - all (bool): Show all containers (default: running only)
    - trunc (bool): Truncate output
    - latest (bool): Show only latest created container
    - since (str): Show containers created since container ID
    - before (str): Show containers created before container ID
    - limit (int): Show 'limit' last created containers
    - size (bool): Display total file sizes
    - filters (dict): Filters to process on container list
    
    Returns:
    list: List of container dictionaries
    """

def inspect_container(container):
    """
    Get detailed information about a container.
    
    Parameters:
    - container (str): Container ID or name
    
    Returns:
    dict: Container configuration and state information
    """

def logs(container, stdout=True, stderr=True, stream=False, 
         timestamps=False, tail='all', since=None, follow=None):
    """
    Get container logs.
    
    Parameters:
    - container (str): Container ID or name
    - stdout (bool): Include stdout
    - stderr (bool): Include stderr
    - stream (bool): Stream logs as generator
    - timestamps (bool): Show timestamps
    - tail (str|int): Number of lines from end ('all' for all)
    - since (int): Show logs since timestamp
    - follow (bool): Follow log output (stream must be True)
    
    Returns:
    bytes|generator: Log data or generator if stream=True
    """

def stats(container, decode=None, stream=True):
    """
    Get container resource usage statistics.
    
    Parameters:
    - container (str): Container ID or name
    - decode (bool): Decode JSON statistics
    - stream (bool): Stream statistics as generator
    
    Returns:
    dict|generator: Statistics data or generator if stream=True
    """

def top(container, ps_args=None):
    """
    Get running processes in a container.
    
    Parameters:
    - container (str): Container ID or name
    - ps_args (str): ps command arguments
    
    Returns:
    dict: Process list with 'Titles' and 'Processes' keys
    """

def diff(container):
    """
    Get changes to container's filesystem.
    
    Parameters:
    - container (str): Container ID or name
    
    Returns:
    list: List of filesystem changes
    """

def port(container, private_port):
    """
    Get port mapping for a container port.
    
    Parameters:
    - container (str): Container ID or name
    - private_port (int): Private port number
    
    Returns:
    list: Port binding information
    """

Container Process Execution

Execute commands within running containers with full control over environment and I/O.

def exec_create(container, cmd, stdout=True, stderr=True, 
                stdin=False, tty=False, privileged=False, user=''):
    """
    Create an exec instance for running commands in a container.
    
    Parameters:
    - container (str): Container ID or name
    - cmd (str|list): Command to execute
    - stdout (bool): Attach to stdout
    - stderr (bool): Attach to stderr
    - stdin (bool): Attach to stdin
    - tty (bool): Allocate pseudo-TTY
    - privileged (bool): Run in privileged mode
    - user (str): User to run command as
    
    Returns:
    dict: Exec instance information with 'Id' key
    """

def exec_start(exec_id, detach=False, tty=False, stream=False, socket=False):
    """
    Start an exec instance.
    
    Parameters:
    - exec_id (str): Exec instance ID
    - detach (bool): Detach from exec
    - tty (bool): Allocate pseudo-TTY
    - stream (bool): Stream output
    - socket (bool): Return socket instead of output
    
    Returns:
    bytes|generator|socket: Command output or generator/socket
    """

def exec_inspect(exec_id):
    """
    Get detailed information about an exec instance.
    
    Parameters:
    - exec_id (str): Exec instance ID
    
    Returns:
    dict: Exec instance details and state
    """

def exec_resize(exec_id, height=None, width=None):
    """
    Resize the TTY of an exec instance.
    
    Parameters:
    - exec_id (str): Exec instance ID
    - height (int): TTY height
    - width (int): TTY width
    
    Returns:
    None
    """

Container Data Operations

File and data transfer operations between containers and the host system.

def attach(container, stdout=True, stderr=True, stream=False, logs=False):
    """
    Attach to a container's I/O streams.
    
    Parameters:
    - container (str): Container ID or name
    - stdout (bool): Attach to stdout
    - stderr (bool): Attach to stderr
    - stream (bool): Stream output
    - logs (bool): Include logs in output
    
    Returns:
    bytes|generator: Output data or generator if stream=True
    """

def attach_socket(container, params=None, ws=False):
    """
    Get a socket to attach to container streams.
    
    Parameters:
    - container (str): Container ID or name
    - params (dict): Additional parameters
    - ws (bool): Use WebSocket connection
    
    Returns:
    socket: Socket for container attachment
    """

def get_archive(container, path):
    """
    Get a tar archive of files from container path.
    
    Parameters:
    - container (str): Container ID or name
    - path (str): Path in container to retrieve
    
    Returns:
    tuple: (tar_data, stat_info) where tar_data is bytes
    """

def put_archive(container, path, data):
    """
    Put a tar archive into container at specified path.
    
    Parameters:
    - container (str): Container ID or name
    - path (str): Path in container to extract to
    - data (bytes): Tar archive data
    
    Returns:
    bool: Success status
    """

def copy(container, resource):
    """
    Copy files from a container (deprecated for API >= 1.20).
    
    Parameters:
    - container (str): Container ID or name
    - resource (str): Path to copy from container
    
    Returns:
    bytes: File data
    """

def export(container):
    """
    Export container filesystem as tar archive.
    
    Parameters:
    - container (str): Container ID or name
    
    Returns:
    generator: Tar archive data stream
    """

def commit(container, repository=None, tag=None, message=None, 
           author=None, changes=None, conf=None):
    """
    Create a new image from container changes.
    
    Parameters:
    - container (str): Container ID or name
    - repository (str): Repository name for new image
    - tag (str): Tag for new image
    - message (str): Commit message
    - author (str): Author of commit
    - changes (list): Dockerfile-like changes
    - conf (dict): Container configuration
    
    Returns:
    str: New image ID
    """

def wait(container, timeout=None):
    """
    Wait for a container to stop and return its exit code.
    
    Parameters:
    - container (str): Container ID or name
    - timeout (int): Timeout in seconds
    
    Returns:
    dict: Exit code information
    """

def resize(container, height, width):
    """
    Resize a container's TTY.
    
    Parameters:
    - container (str): Container ID or name
    - height (int): TTY height
    - width (int): TTY width
    
    Returns:
    None
    """

Container Resource Management

Update and manage container resource constraints and configurations.

def update_container(container, blkio_weight=None, cpu_period=None, 
                    cpu_quota=None, cpu_shares=None, cpuset_cpus=None, 
                    cpuset_mems=None, mem_limit=None, mem_reservation=None, 
                    memswap_limit=None, kernel_memory=None):
    """
    Update container resource constraints.
    
    Parameters:
    - container (str): Container ID or name
    - blkio_weight (int): Block IO weight (10-1000)
    - cpu_period (int): CPU CFS period
    - cpu_quota (int): CPU CFS quota
    - cpu_shares (int): CPU shares weight
    - cpuset_cpus (str): CPUs to use
    - cpuset_mems (str): Memory nodes to use
    - mem_limit (int): Memory limit in bytes
    - mem_reservation (int): Memory soft limit
    - memswap_limit (int): Memory + swap limit
    - kernel_memory (int): Kernel memory limit
    
    Returns:
    dict: Update response
    """

Configuration Helper Functions

Functions for building complex container configurations with proper validation and formatting.

def create_container_config(*args, **kwargs):
    """
    Create a container configuration dictionary.
    
    Returns:
    dict: Container configuration
    """

def create_host_config(binds=None, port_bindings=None, lxc_conf=None, 
                      publish_all_ports=False, links=None, privileged=False, 
                      dns=None, dns_search=None, volumes_from=None, 
                      network_mode=None, restart_policy=None, cap_add=None, 
                      cap_drop=None, devices=None, extra_hosts=None, 
                      read_only=None, pid_mode=None, ipc_mode=None, 
                      security_opt=None, ulimits=None, log_config=None, 
                      mem_limit=None, memswap_limit=None, mem_reservation=None, 
                      kernel_memory=None, mem_swappiness=None, 
                      cgroup_parent=None, group_add=None, cpu_quota=None, 
                      cpu_period=None, blkio_weight=None, 
                      blkio_weight_device=None, device_read_bps=None, 
                      device_write_bps=None, device_read_iops=None, 
                      device_write_iops=None, oom_kill_disable=None, 
                      shm_size=None, sysctls=None, tmpfs=None, 
                      oom_score_adj=None, dns_opt=None, 
                      cpu_shares=None, cpuset_cpus=None, cpuset_mems=None, 
                      userns_mode=None, pids_limit=None):
    """
    Create host configuration for containers.
    
    Parameters:
    - binds (dict|list): Volume bindings
    - port_bindings (dict): Port bindings
    - lxc_conf (dict): LXC configuration
    - publish_all_ports (bool): Publish all exposed ports
    - links (list): Container links
    - privileged (bool): Privileged mode
    - dns (list): DNS servers
    - dns_search (list): DNS search domains
    - volumes_from (list): Mount volumes from containers
    - network_mode (str): Network mode
    - restart_policy (dict): Restart policy
    - cap_add (list): Linux capabilities to add
    - cap_drop (list): Linux capabilities to drop
    - devices (list): Device mappings
    - extra_hosts (list): Extra hosts entries
    - read_only (bool): Read-only root filesystem
    - pid_mode (str): PID namespace mode
    - ipc_mode (str): IPC namespace mode
    - security_opt (list): Security options
    - ulimits (list): Resource limits
    - log_config (LogConfig): Logging configuration
    - mem_limit (int): Memory limit
    - memswap_limit (int): Memory + swap limit
    - mem_reservation (int): Memory soft limit
    - kernel_memory (int): Kernel memory limit
    - mem_swappiness (int): Memory swappiness (0-100)
    - cgroup_parent (str): Parent cgroup
    - group_add (list): Additional groups
    - cpu_quota (int): CPU quota
    - cpu_period (int): CPU period
    - blkio_weight (int): Block IO weight
    - blkio_weight_device (list): Block IO weight devices
    - device_read_bps (list): Device read limits (bytes/sec)
    - device_write_bps (list): Device write limits (bytes/sec)
    - device_read_iops (list): Device read limits (operations/sec)
    - device_write_iops (list): Device write limits (operations/sec)
    - oom_kill_disable (bool): Disable OOM killer
    - shm_size (int): Shared memory size
    - sysctls (dict): Kernel parameters
    - tmpfs (dict): Tmpfs mounts
    - oom_score_adj (int): OOM score adjustment
    - dns_opt (list): DNS options
    - cpu_shares (int): CPU shares
    - cpuset_cpus (str): CPUs to use
    - cpuset_mems (str): Memory nodes to use
    - userns_mode (str): User namespace mode
    - pids_limit (int): PID limit
    
    Returns:
    dict: Host configuration
    """

def create_container_from_config(config, name=None):
    """
    Create a container from a configuration dictionary.
    
    Parameters:
    - config (dict): Container configuration
    - name (str): Container name
    
    Returns:
    dict: Container creation response
    """

Usage Examples

Basic Container Operations

import docker

client = docker.Client()

# Create and run a simple container
container = client.create_container(
    image='ubuntu:latest',
    command='echo "Hello, Docker!"',
    name='hello-container'
)

client.start(container)
client.wait(container)

# Get container output
logs = client.logs(container)
print(logs.decode('utf-8'))  # "Hello, Docker!"

# Cleanup
client.remove_container(container)

Interactive Container with TTY

# Create interactive container
container = client.create_container(
    image='ubuntu:latest',
    command='/bin/bash',
    tty=True,
    stdin_open=True,
    detach=True,
    name='interactive-container'
)

client.start(container)

# Execute commands in the running container
exec_instance = client.exec_create(
    container,
    'ls -la /tmp',
    stdout=True,
    stderr=True
)

output = client.exec_start(exec_instance)
print(output.decode('utf-8'))

Container with Custom Configuration

# Create container with resource limits and volume mounts
host_config = client.create_host_config(
    binds={'/host/path': {'bind': '/container/path', 'mode': 'rw'}},
    port_bindings={'8080/tcp': 8080},
    mem_limit='512m',
    cpu_shares=512,
    ulimits=[docker.types.Ulimit(name='nofile', soft=1024, hard=2048)]
)

container = client.create_container(
    image='nginx:latest',
    ports=['8080/tcp'],
    volumes=['/container/path'],
    host_config=host_config,
    environment={'ENV_VAR': 'value'},
    labels={'app': 'web', 'version': '1.0'},
    name='web-server'
)

client.start(container)

Install with Tessl CLI

npx tessl i tessl/pypi-docker-py

docs

containers.md

images.md

index.md

networking.md

swarm.md

utilities.md

tile.json