A Python library for the Docker Engine API.
—
Complete container lifecycle management including creation, execution, monitoring, and resource control with support for advanced features like container attachment, file transfer, and process execution.
High-level container management operations accessible via client.containers.
class ContainerCollection:
def run(self, image, command=None, **kwargs):
"""
Create and start a container.
Args:
image (str): Image name or ID to run
command (str or list): Command to execute in container
**kwargs: Container configuration options
Returns:
Container: Running container instance
Common kwargs:
auto_remove (bool): Remove container when it exits
detach (bool): Run in background (default: False)
environment (dict or list): Environment variables
name (str): Container name
ports (dict): Port mappings {'container_port': host_port}
volumes (dict): Volume mounts {'host_path': {'bind': '/container/path', 'mode': 'rw'}}
working_dir (str): Working directory inside container
user (str): User to run as
network (str): Network to connect to
restart_policy (dict): Restart policy configuration
"""
def create(self, image, command=None, **kwargs):
"""
Create a container without starting it.
Args:
image (str): Image name or ID
command (str or list): Command to execute
**kwargs: Same as run() method
Returns:
Container: Container instance (not started)
"""
def get(self, container_id):
"""
Get a container by ID or name.
Args:
container_id (str): Container ID or name
Returns:
Container: Container instance
Raises:
NotFound: If container doesn't exist
"""
def list(self, all=False, before=None, filters=None, limit=None, since=None, sparse=False):
"""
List containers.
Args:
all (bool): Include stopped containers
before (str): Show containers created before this container ID
filters (dict): Filter results by status, label, etc.
limit (int): Maximum number of containers to return
since (str): Show containers created since this container ID
sparse (bool): Return limited information
Returns:
list[Container]: List of container instances
"""
def prune(self, filters=None):
"""
Remove unused containers.
Args:
filters (dict): Filters to apply when pruning
Returns:
dict: Pruning results with space reclaimed
"""Individual container instance with lifecycle and operational methods.
class Container:
"""
A Docker container instance.
Properties:
id (str): Full container ID
short_id (str): Short container ID (12 characters)
name (str): Container name
image (Image): Container image object
labels (dict): Container labels
status (str): Container status ('running', 'exited', 'paused', etc.)
health (str): Healthcheck status ('healthy', 'unhealthy', 'starting', 'unknown')
ports (dict): Exposed port mappings
attrs (dict): Raw container attributes from Docker API
"""def start(self, **kwargs):
"""
Start the container.
Raises:
APIError: If container cannot be started
"""
def stop(self, timeout=10):
"""
Stop the container gracefully.
Args:
timeout (int): Seconds to wait before killing container
"""
def restart(self, timeout=10):
"""
Restart the container.
Args:
timeout (int): Seconds to wait before killing during restart
"""
def kill(self, signal='SIGKILL'):
"""
Kill the container with a signal.
Args:
signal (str or int): Signal to send (default: SIGKILL)
"""
def pause(self):
"""Pause all processes in the container."""
def unpause(self):
"""Unpause all processes in the container."""
def remove(self, v=False, link=False, force=False):
"""
Remove the container.
Args:
v (bool): Remove associated anonymous volumes
link (bool): Remove specified link
force (bool): Force removal of running container
"""
def wait(self, timeout=None, condition='not-running'):
"""
Wait for container to stop.
Args:
timeout (int): Timeout in seconds
condition (str): Condition to wait for ('not-running', 'next-exit', 'removed')
Returns:
dict: Exit status and error information
"""def exec_run(self, cmd, stdout=True, stderr=True, stdin=False, tty=False, privileged=False, user='', environment=None, workdir=None, detach=False, stream=False, socket=False, demux=False):
"""
Execute a command inside the container.
Args:
cmd (str or list): Command to execute
stdout (bool): Capture stdout
stderr (bool): Capture stderr
stdin (bool): Enable stdin
tty (bool): Allocate pseudo-TTY
privileged (bool): Run with extended privileges
user (str): User to run command as
environment (list): Environment variables ['VAR=value']
workdir (str): Working directory for command
detach (bool): Run in background
stream (bool): Stream output
socket (bool): Return socket instead of output
demux (bool): Separate stdout/stderr streams
Returns:
ExecResult: Named tuple with (exit_code, output) or generator if stream=True
"""
def top(self, ps_args=None):
"""
Get running processes in container.
Args:
ps_args (str): Arguments to ps command
Returns:
dict: Process information with titles and processes
"""def logs(self, stdout=True, stderr=True, stream=False, timestamps=False, tail='all', since=None, follow=None, until=None):
"""
Get container logs.
Args:
stdout (bool): Include stdout
stderr (bool): Include stderr
stream (bool): Stream logs continuously
timestamps (bool): Include timestamps
tail (str or int): Number of lines from end ('all' for all)
since (datetime or str): Show logs since timestamp
follow (bool): Follow log output (same as stream)
until (datetime or str): Show logs until timestamp
Returns:
bytes or generator: Log output or log stream if stream=True
"""
def stats(self, decode=None, stream=True):
"""
Get container resource usage statistics.
Args:
decode (bool): Decode JSON statistics
stream (bool): Stream statistics continuously
Returns:
dict or generator: Resource usage statistics
"""
def attach(self, **kwargs):
"""
Attach to container's stdin/stdout/stderr.
Args:
stdout (bool): Attach to stdout (default: True)
stderr (bool): Attach to stderr (default: True)
stream (bool): Stream output (default: True)
logs (bool): Include previous output (default: False)
Returns:
generator: Output stream
"""
def attach_socket(self, **kwargs):
"""
Get a socket for container attachment.
Args:
params (dict): Attachment parameters
ws (bool): Use WebSocket for attachment
Returns:
socket: Raw socket for attachment
"""def diff(self):
"""
Inspect changes on container's filesystem since creation.
Returns:
list: List of dictionaries containing 'Path' and 'Kind' attributes
Kind values: 0=Modified, 1=Added, 2=Deleted
"""
def put_archive(self, path, data):
"""
Upload tar archive to container filesystem.
Args:
path (str): Destination path in container
data (bytes): Tar archive data
Returns:
bool: True if successful
"""
def get_archive(self, path, chunk_size=2097152):
"""
Download tar archive from container filesystem.
Args:
path (str): Source path in container
chunk_size (int): Chunk size for streaming
Returns:
tuple: (tar_stream, stat_info)
Raises:
NotFound: If path doesn't exist
"""
def export(self, chunk_size=2097152):
"""
Export container filesystem as tar archive.
Args:
chunk_size (int): Chunk size for streaming
Returns:
generator: Tar archive data chunks
"""def update(self, **kwargs):
"""
Update container resource configuration.
Args:
**kwargs: Resource constraints to update
Common kwargs:
mem_limit (str or int): Memory limit
memswap_limit (str or int): Memory + swap limit
cpu_shares (int): CPU shares (relative weight)
cpu_period (int): CPU CFS period
cpu_quota (int): CPU CFS quota
cpuset_cpus (str): CPUs to use (0-3, 0,1)
cpuset_mems (str): Memory nodes to use
restart_policy (dict): Restart policy
"""
def commit(self, repository=None, tag=None, message=None, author=None, changes=None, conf=None):
"""
Create new image from container changes.
Args:
repository (str): Repository name for new image
tag (str): Tag for new image
message (str): Commit message
author (str): Author information
changes (list): Dockerfile instructions to apply
conf (dict): Container configuration changes
Returns:
Image: New image created from container
"""
def rename(self, name):
"""
Rename the container.
Args:
name (str): New container name
"""
def resize(self, height, width):
"""
Resize container TTY.
Args:
height (int): TTY height
width (int): TTY width
"""import docker
client = docker.from_env()
# Run a simple container
container = client.containers.run(
'ubuntu:20.04',
'echo "Hello World"',
remove=True
)
# Run detached container with port mapping
web_container = client.containers.run(
'nginx:latest',
detach=True,
ports={'80/tcp': 8080},
name='my-nginx'
)
# Get container and check status
container = client.containers.get('my-nginx')
print(f"Status: {container.status}")
# Stop and remove
container.stop()
container.remove()# Run with volumes, environment variables, and resource limits
container = client.containers.run(
'python:3.9',
'python /app/main.py',
detach=True,
environment={
'DATABASE_URL': 'postgresql://localhost/mydb',
'DEBUG': 'true'
},
volumes={
'/host/app': {'bind': '/app', 'mode': 'ro'},
'/host/data': {'bind': '/data', 'mode': 'rw'}
},
ports={'5000/tcp': 5000},
mem_limit='512m',
cpu_shares=512,
restart_policy={'Name': 'unless-stopped'},
name='my-python-app'
)container = client.containers.get('my-app')
# Execute command in running container
result = container.exec_run('ls -la /app')
print(f"Exit code: {result.exit_code}")
print(f"Output: {result.output.decode()}")
# Interactive execution with TTY
exec_result = container.exec_run(
'bash',
stdin=True,
tty=True,
socket=True
)
# Get running processes
processes = container.top()
for process in processes['Processes']:
print(f"PID: {process[1]}, Command: {process[7]}")
# Stream logs
for line in container.logs(stream=True, follow=True):
print(line.decode().strip())
# Monitor resource usage
for stats in container.stats(decode=True):
cpu_percent = stats['cpu_stats']['cpu_usage']['total_usage']
memory_usage = stats['memory_stats']['usage']
print(f"CPU: {cpu_percent}, Memory: {memory_usage}")import tarfile
import io
container = client.containers.get('my-app')
# Upload file to container
tar_data = io.BytesIO()
with tarfile.open(fileobj=tar_data, mode='w') as tar:
tar.add('/local/config.json', arcname='config.json')
tar_data.seek(0)
container.put_archive('/app/', tar_data.getvalue())
# Download file from container
archive, stats = container.get_archive('/app/output.log')
with open('/local/output.log', 'wb') as f:
for chunk in archive:
f.write(chunk)
# Export entire container filesystem
with open('/local/container_export.tar', 'wb') as f:
for chunk in container.export():
f.write(chunk)# Create container without starting
container = client.containers.create(
'redis:alpine',
name='my-redis',
ports={'6379/tcp': 6379}
)
# Start when ready
container.start()
# Pause/unpause operations
container.pause()
print(f"Status: {container.status}") # paused
container.unpause()
print(f"Status: {container.status}") # running
# Graceful shutdown with timeout
container.stop(timeout=30)
# Wait for container to exit
result = container.wait()
print(f"Exit code: {result['StatusCode']}")
# Force removal
container.remove(force=True)