Docker Networking Fundamentals
Understand Docker networking: bridge, host, overlay, and macvlan drivers. Create custom networks, connect containers, enable DNS discovery, and isolate services.
Detailed Explanation
Docker Network Drivers
Docker supports several network drivers, each suited for different scenarios.
Bridge (Default)
The default network driver. Containers on the same bridge can communicate using IP addresses:
# Create a custom bridge network
docker network create my-network
# Run containers on the same network
docker run -d --name api --network my-network my-api
docker run -d --name db --network my-network postgres:16
On custom bridge networks, containers can reach each other by name (Docker DNS):
# From the api container:
ping db # resolves to the db container's IP
Host Network
The container shares the host's network stack directly. No port mapping needed:
docker run --network host nginx
# Nginx is accessible on host's port 80 directly
Network Management Commands
# List networks
docker network ls
# Inspect a network (see connected containers)
docker network inspect my-network
# Connect a running container to a network
docker network connect my-network existing-container
# Disconnect from a network
docker network disconnect my-network my-container
# Remove unused networks
docker network prune
Network Aliases
Give containers multiple DNS names within a network:
docker network connect --alias database my-network postgres-container
Subnet Configuration
docker network create \
--driver bridge \
--subnet 172.28.0.0/16 \
--gateway 172.28.0.1 \
my-custom-net
Use Case
Setting up microservice communication where services discover each other by name, isolating frontend and backend networks for security, and configuring custom subnets for integration with existing infrastructure.