A Python library for the Docker Engine API.
—
Docker network creation, configuration, and container connectivity management with support for custom networks, network drivers, and advanced networking features.
class NetworkCollection:
def create(self, name, **kwargs):
"""
Create a network.
Args:
name (str): Network name
**kwargs: Network configuration options
Returns:
Network: Created network instance
Common kwargs:
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 networks
internal (bool): Restrict external access
labels (dict): Network labels
enable_ipv6 (bool): Enable IPv6 networking
attachable (bool): Allow manual container attachment
scope (str): Network scope ('local', 'global', 'swarm')
ingress (bool): Create ingress network
"""
def get(self, network_id):
"""
Get a network by ID or name.
Args:
network_id (str): Network ID or name
Returns:
Network: Network instance
"""
def list(self, names=None, ids=None, filters=None):
"""
List networks.
Args:
names (list): Filter by network names
ids (list): Filter by network IDs
filters (dict): Additional filters
Returns:
list[Network]: List of network instances
"""
def prune(self, filters=None):
"""
Remove unused networks.
Args:
filters (dict): Filters for pruning
Returns:
dict: Pruning results
"""class Network:
"""
A Docker network instance.
Properties:
id (str): Network ID
name (str): Network name
attrs (dict): Raw network attributes
"""
def connect(self, container, **kwargs):
"""
Connect a container to this network.
Args:
container (Container or str): Container to connect
**kwargs: Connection options
Common kwargs:
aliases (list): Network aliases for container
links (list): Links to other containers
ipv4_address (str): Static IPv4 address
ipv6_address (str): Static IPv6 address
link_local_ips (list): Link-local IP addresses
"""
def disconnect(self, container, **kwargs):
"""
Disconnect a container from this network.
Args:
container (Container or str): Container to disconnect
**kwargs: Disconnection options
Common kwargs:
force (bool): Force disconnection
"""
def remove(self):
"""Remove the network."""import docker
client = docker.from_env()
# Create custom network
network = client.networks.create(
'my-app-network',
driver='bridge',
options={'com.docker.network.bridge.name': 'my-bridge'},
ipam={
'Config': [{
'Subnet': '172.20.0.0/16',
'Gateway': '172.20.0.1'
}]
}
)
# Connect containers
container1 = client.containers.run('nginx', detach=True)
container2 = client.containers.run('redis', detach=True)
network.connect(container1, aliases=['web'])
network.connect(container2, ipv4_address='172.20.0.10')
# List networks
for net in client.networks.list():
print(f"Network: {net.name}, Driver: {net.attrs['Driver']}")