Containers talking to each other via localhost:port? That’s so 2015. Welcome to the civilized world of Docker networks.
Create a network#
1
2
3
4
5
6
7
8
| # Create bridge network (default)
docker network create my-network
# Create with specific driver
docker network create --driver bridge my-bridge-network
# Create with subnet
docker network create --subnet=172.18.0.0/16 my-network
|
List networks#
1
2
3
4
5
| # List all networks
docker network ls
# Inspect network details
docker network inspect my-network
|
Use network with containers#
1
2
3
4
5
6
7
8
| # Run container on specific network
docker run -d --name web --network my-network nginx
# Connect running container to network
docker network connect my-network existing-container
# Disconnect container from network
docker network disconnect my-network container-name
|
Remove networks#
1
2
3
4
5
| # Remove specific network
docker network rm my-network
# Remove all unused networks
docker network prune
|
Multi-container example#
1
2
3
4
5
6
7
8
9
10
| # Create network
docker network create app-network
# Run database on network
docker run -d --name db --network app-network postgres
# Run app on same network (can reach db via hostname 'db')
docker run -d --name api --network app-network \
-e DATABASE_HOST=db \
my-api-image
|
Notes#
- Containers on same network can communicate via container names
- Default bridge network requires
--link (deprecated) - Custom networks provide automatic DNS resolution
- Network name becomes resolvable hostname for containers