A comprehensive Python client library for the Docker Remote API enabling programmatic control of containers, images, networks, and volumes.
—
Docker network operations for creating custom networks, connecting containers, and managing network isolation. Supports bridge, overlay, and custom network drivers with advanced configuration options including IPAM (IP Address Management) and multi-host networking capabilities.
Core network management functions for creating, inspecting, and removing Docker networks.
def networks(names=None, ids=None):
"""
List Docker networks.
Parameters:
- names (list): Filter by network names
- ids (list): Filter by network IDs
Returns:
list: List of network dictionaries with configuration details
"""
def create_network(name, driver=None, options=None, ipam=None,
check_duplicate=None, internal=False, labels=None,
enable_ipv6=False):
"""
Create a new Docker network.
Parameters:
- name (str): Network name
- driver (str): Network driver ('bridge', 'overlay', 'macvlan', etc.)
- options (dict): Driver-specific options
- ipam (dict): IP Address Management configuration
- check_duplicate (bool): Check for duplicate network names
- internal (bool): Restrict external access to network
- labels (dict): Network labels
- enable_ipv6 (bool): Enable IPv6 on network
Returns:
dict: Network creation response with 'Id' key
"""
def inspect_network(net_id):
"""
Get detailed information about a network.
Parameters:
- net_id (str): Network ID or name
Returns:
dict: Network configuration and state information
"""
def remove_network(net_id):
"""
Remove a network.
Parameters:
- net_id (str): Network ID or name
Returns:
None
"""Functions for connecting and disconnecting containers to/from networks with advanced configuration.
def connect_container_to_network(container, net_id, ipv4_address=None,
ipv6_address=None, aliases=None,
links=None, link_local_ips=None):
"""
Connect a container to a network.
Parameters:
- container (str): Container ID or name
- net_id (str): Network ID or name
- ipv4_address (str): IPv4 address for container on network
- ipv6_address (str): IPv6 address for container on network
- aliases (list): Network-scoped aliases for container
- links (list): Links to other containers (deprecated)
- link_local_ips (list): Link-local IPv4/IPv6 addresses
Returns:
None
"""
def disconnect_container_from_network(container, net_id, force=False):
"""
Disconnect a container from a network.
Parameters:
- container (str): Container ID or name
- net_id (str): Network ID or name
- force (bool): Force disconnect
Returns:
None
"""Utility functions for building complex network configurations.
def create_networking_config(endpoints_config=None):
"""
Create networking configuration for container creation.
Parameters:
- endpoints_config (dict): Endpoint configurations keyed by network name
Returns:
dict: Networking configuration
"""
def create_endpoint_config(version, aliases=None, links=None,
ipv4_address=None, ipv6_address=None,
link_local_ips=None):
"""
Create endpoint configuration for network connection.
Parameters:
- version (str): API version
- aliases (list): Network-scoped aliases
- links (list): Container links (deprecated)
- ipv4_address (str): Static IPv4 address
- ipv6_address (str): Static IPv6 address
- link_local_ips (list): Link-local addresses
Returns:
dict: Endpoint configuration
"""
def create_ipam_config(driver='default', pool_configs=None):
"""
Create IP Address Management configuration.
Parameters:
- driver (str): IPAM driver name
- pool_configs (list): List of IPAM pool configurations
Returns:
dict: IPAM configuration
"""
def create_ipam_pool(subnet=None, iprange=None, gateway=None, aux_addresses=None):
"""
Create IPAM pool configuration.
Parameters:
- subnet (str): Subnet in CIDR format
- iprange (str): IP range in CIDR format
- gateway (str): Gateway IP address
- aux_addresses (dict): Auxiliary addresses
Returns:
dict: IPAM pool configuration
"""Docker supports multiple network drivers for different use cases:
Default driver for single-host networking with port mapping and container isolation.
Multi-host networking for Docker Swarm clusters with built-in service discovery.
Remove network isolation and use host networking stack directly.
Disable all networking for maximum isolation.
Third-party drivers for specialized networking requirements.
import docker
client = docker.Client()
# List existing networks
networks = client.networks()
for network in networks:
print(f"Name: {network['Name']}, Driver: {network['Driver']}")
# Create a custom bridge network
network = client.create_network(
name='my-network',
driver='bridge',
options={
'com.docker.network.bridge.name': 'my-bridge'
},
labels={'environment': 'development'}
)
print(f"Created network: {network['Id']}")
# Inspect network details
network_info = client.inspect_network('my-network')
print(f"Subnet: {network_info['IPAM']['Config'][0]['Subnet']}")
# Remove network
client.remove_network('my-network')# Create a network
client.create_network('app-network', driver='bridge')
# Create containers
web_container = client.create_container(
image='nginx:latest',
name='web-server'
)
db_container = client.create_container(
image='postgres:latest',
name='database',
environment={'POSTGRES_PASSWORD': 'secret'}
)
# Start containers
client.start(web_container)
client.start(db_container)
# Connect containers to network with aliases
client.connect_container_to_network(
web_container,
'app-network',
aliases=['web', 'frontend']
)
client.connect_container_to_network(
db_container,
'app-network',
aliases=['db', 'database'],
ipv4_address='172.20.0.100' # Static IP
)
# Containers can now communicate using aliases
# web-server can reach database at 'db' or 'database'# Create network with custom IPAM configuration
ipam_pool = client.create_ipam_pool(
subnet='192.168.100.0/24',
gateway='192.168.100.1',
aux_addresses={
'reserved1': '192.168.100.2',
'reserved2': '192.168.100.3'
}
)
ipam_config = client.create_ipam_config(
driver='default',
pool_configs=[ipam_pool]
)
network = client.create_network(
name='custom-network',
driver='bridge',
ipam=ipam_config,
options={
'com.docker.network.bridge.enable_icc': 'true',
'com.docker.network.bridge.enable_ip_masquerade': 'true',
'com.docker.network.driver.mtu': '1500'
},
labels={
'project': 'myapp',
'environment': 'production'
}
)# Create application network
client.create_network('myapp-network', driver='bridge')
# Create database container
db_container = client.create_container(
image='postgres:13',
name='myapp-db',
environment={
'POSTGRES_DB': 'myapp',
'POSTGRES_USER': 'appuser',
'POSTGRES_PASSWORD': 'secret'
},
volumes=['/var/lib/postgresql/data']
)
# Create Redis cache container
cache_container = client.create_container(
image='redis:6-alpine',
name='myapp-cache'
)
# Create web application container
web_container = client.create_container(
image='myapp:latest',
name='myapp-web',
ports=['8000/tcp'],
environment={
'DATABASE_URL': 'postgresql://appuser:secret@db:5432/myapp',
'REDIS_URL': 'redis://cache:6379'
}
)
# Start all containers
for container in [db_container, cache_container, web_container]:
client.start(container)
# Connect all containers to application network
client.connect_container_to_network(db_container, 'myapp-network', aliases=['db'])
client.connect_container_to_network(cache_container, 'myapp-network', aliases=['cache'])
client.connect_container_to_network(web_container, 'myapp-network', aliases=['web'])
# Expose web container port to host
host_config = client.create_host_config(
port_bindings={'8000/tcp': 8000}
)
# Web container can reach database at 'db:5432' and cache at 'cache:6379'# Create isolated networks for different environments
networks = ['frontend-network', 'backend-network']
for network_name in networks:
client.create_network(
name=network_name,
driver='bridge',
internal=True, # No external access
labels={'isolation': 'true'}
)
# Frontend containers (web servers, load balancers)
frontend_container = client.create_container(
image='nginx:latest',
name='frontend'
)
# Backend containers (application servers, databases)
backend_container = client.create_container(
image='myapp-backend:latest',
name='backend'
)
database_container = client.create_container(
image='postgres:13',
name='database'
)
# Start containers
for container in [frontend_container, backend_container, database_container]:
client.start(container)
# Connect to appropriate networks
client.connect_container_to_network(frontend_container, 'frontend-network')
client.connect_container_to_network(backend_container, 'frontend-network') # Bridge between networks
client.connect_container_to_network(backend_container, 'backend-network')
client.connect_container_to_network(database_container, 'backend-network')
# Frontend can reach backend, backend can reach database,
# but frontend cannot directly reach database# Function to create environment-specific networks
def create_environment_network(env_name):
network_name = f'{env_name}-network'
# Create network with environment-specific configuration
network = client.create_network(
name=network_name,
driver='bridge',
labels={
'environment': env_name,
'created_by': 'docker-py'
},
options={
'com.docker.network.bridge.name': f'{env_name}-br0'
}
)
return network['Id']
# Create networks for different environments
environments = ['development', 'staging', 'production']
network_ids = {}
for env in environments:
network_ids[env] = create_environment_network(env)
print(f"Created {env} network: {network_ids[env][:12]}")
# Clean up networks
for env in environments:
try:
client.remove_network(f'{env}-network')
print(f"Removed {env} network")
except Exception as e:
print(f"Error removing {env} network: {e}")Install with Tessl CLI
npx tessl i tessl/pypi-docker-py