A Python library for the Docker Engine API.
—
Docker context management for connecting to different Docker hosts and orchestrators with persistent configuration and credential storage.
Docker context representation that encapsulates connection information, TLS configuration, and orchestrator settings for Docker hosts.
class Context:
def __init__(self, name, orchestrator=None, host=None, endpoints=None, tls=False):
"""
Create a new Docker context.
Args:
name (str): Context name
orchestrator (str): Orchestrator type ('swarm', 'kubernetes', etc.)
host (str): Docker host URL
endpoints (dict): Endpoint configuration
tls (bool): Enable TLS
"""
def set_endpoint(self, name='docker', host=None, tls_cfg=None, skip_tls_verify=False, def_namespace=None):
"""
Configure context endpoint.
Args:
name (str): Endpoint name (default: 'docker')
host (str): Host URL
tls_cfg (TLSConfig): TLS configuration
skip_tls_verify (bool): Skip TLS verification
def_namespace (str): Default namespace for Kubernetes
"""
def inspect(self):
"""
Get context metadata and configuration.
Returns:
dict: Context information including name, metadata, endpoints
"""
def save(self):
"""
Save context to disk for persistent storage.
"""
def remove(self):
"""
Remove context from disk.
"""
@classmethod
def load_context(cls, name):
"""
Load existing context from disk.
Args:
name (str): Context name
Returns:
Context: Context instance or None if not found
"""
# Properties
name: str # Context name
orchestrator: str # Orchestrator type
endpoints: dict # Endpoint configurations
tls_cfg: dict # TLS configurations
meta_path: str # Metadata storage path
tls_path: str # TLS certificate storage pathContext management operations for creating, listing, retrieving, and managing Docker contexts.
class ContextAPI:
DEFAULT_CONTEXT: Context # Default context instance
@classmethod
def create_context(cls, name, orchestrator=None, host=None, tls_cfg=None, default_namespace=None, skip_tls_verify=False):
"""
Create a new Docker context.
Args:
name (str): Context name (required)
orchestrator (str): Orchestrator type ('swarm', 'kubernetes')
host (str): Docker host URL
tls_cfg (TLSConfig): TLS configuration
default_namespace (str): Default namespace for Kubernetes
skip_tls_verify (bool): Skip TLS verification
Returns:
Context: Created context instance
Raises:
MissingContextParameter: If name is not provided
ContextAlreadyExists: If context with name already exists
ContextException: If name is 'default' (reserved)
"""
@classmethod
def get_context(cls, name=None):
"""
Retrieve a context by name.
Args:
name (str): Context name (defaults to current context)
Returns:
Context: Context instance or None if not found
"""
@classmethod
def list_contexts(cls):
"""
List all available contexts.
Returns:
list: List of context dictionaries with metadata
"""
@classmethod
def remove_context(cls, name):
"""
Remove a context.
Args:
name (str): Context name to remove
Raises:
ContextNotFound: If context doesn't exist
ContextException: If trying to remove default context
"""
@classmethod
def get_current_context_name(cls):
"""
Get the name of the currently active context.
Returns:
str: Current context name
"""from docker.context import Context, ContextAPI
# Create a new context
ctx = ContextAPI.create_context(
name='production',
host='tcp://prod.example.com:2376',
tls_cfg=True
)
# List all contexts
contexts = ContextAPI.list_contexts()
for context in contexts:
print(f"Context: {context['Name']}")
print(f"Host: {context['Endpoints']['docker']['Host']}")
# Get current context
current = ContextAPI.get_context()
print(f"Current context: {current.name}")
# Switch to a different context
prod_ctx = ContextAPI.get_context('production')
if prod_ctx:
print(f"Using production context: {prod_ctx.endpoints}")from docker.context import ContextAPI
from docker.tls import TLSConfig
# Create TLS configuration
tls_config = TLSConfig(
client_cert=('/path/to/client-cert.pem', '/path/to/client-key.pem'),
ca_cert='/path/to/ca.pem',
verify=True
)
# Create secure context
secure_ctx = ContextAPI.create_context(
name='secure-remote',
host='tcp://secure.example.com:2376',
tls_cfg=tls_config
)
print(f"Created secure context: {secure_ctx.name}")
print(f"Endpoints: {secure_ctx.endpoints}")from docker.context import ContextAPI
# Create Kubernetes context
k8s_ctx = ContextAPI.create_context(
name='k8s-cluster',
orchestrator='kubernetes',
host='https://k8s.example.com:6443',
default_namespace='production'
)
# Inspect the context
metadata = k8s_ctx.inspect()
print(f"Context metadata: {metadata}")from docker.context import ContextAPI
from docker.errors import (
ContextAlreadyExists,
ContextNotFound,
MissingContextParameter,
ContextException
)
try:
# Create context
ctx = ContextAPI.create_context(name='test-context')
print(f"Created context: {ctx.name}")
except MissingContextParameter as e:
print(f"Missing parameter: {e.param}")
except ContextAlreadyExists as e:
print(f"Context already exists: {e.name}")
# Get existing context instead
ctx = ContextAPI.get_context(e.name)
except ContextException as e:
print(f"Context operation failed: {e.msg}")
# Safe context retrieval
try:
ctx = ContextAPI.get_context('nonexistent')
if ctx:
print(f"Found context: {ctx.name}")
else:
print("Context not found")
except ContextNotFound as e:
print(f"Context not found: {e.name}")
# Remove context safely
try:
ContextAPI.remove_context('test-context')
print("Context removed successfully")
except ContextNotFound as e:
print(f"Cannot remove - context not found: {e.name}")
except ContextException as e:
print(f"Cannot remove context: {e.msg}")from docker.context import Context, ContextAPI
# Load context from disk
ctx = Context.load_context('production')
if ctx:
print(f"Loaded context: {ctx.name}")
print(f"Meta path: {ctx.meta_path}")
print(f"TLS path: {ctx.tls_path}")
# Create context with multiple endpoints
multi_ctx = Context(
name='multi-endpoint',
endpoints={
'docker': {
'Host': 'tcp://docker.example.com:2376',
'SkipTLSVerify': False
},
'kubernetes': {
'Host': 'https://k8s.example.com:6443',
'DefaultNamespace': 'default'
}
}
)
# Configure additional endpoint
multi_ctx.set_endpoint(
name='swarm',
host='tcp://swarm.example.com:2377',
skip_tls_verify=False
)
# Save context
multi_ctx.save()import docker
from docker.context import ContextAPI
# Get production context
prod_ctx = ContextAPI.get_context('production')
if prod_ctx:
# Use context configuration to create client
endpoint = prod_ctx.endpoints.get('docker', {})
client = docker.DockerClient(
base_url=endpoint.get('Host'),
tls=not endpoint.get('SkipTLSVerify', True)
)
# Use client with production context
containers = client.containers.list()
print(f"Production containers: {len(containers)}")