Docker Networks
Table of contents
Some useful commands
# List all networks
docker network ls
docker network inspect network-name
# Disconnect any containers using this network
docker network disconnect network-name my-container
docker network rm network-name
# Remove unused networks
docker network prune
How do I talk to the container?
When a container is created, none of the ports inside the container are exposed.
In order for the Docker host (your computer) or other containers to talk to it, it must first publish a port.
The following maps a port 1234 inside a container to 4321 on Docker host.
docker create -p 1234:4321
Now you can communicate with the container via http://localhost:4321
.
How can containers talk to each other?
If the containers are running on the same Docker daemon host (ie. all running on your computer), then the easiest way is to put them on the same bridge network.
Default bridge network
Check the existing docker networks with
docker network ls
You will see a network with the name bridge
. That is the default bridge network.
Every started container is automatically added to the default bridge network if you didn’t specify anything else.
With the default bridge you talk to other containers by using their IP Address.
docker inspect my-container | grep IPAddress
Downsides to using the default bridge network:
- Using an IP address sucks: it is not immediate which container I’m referring to.
- Every container can talk to every other container, which may cause security issues.
User-defined bridge network
You can instead add a user-defined bridge network.
It still uses the same bridge
driver, but unlike the default bridge not everyone is invited to it.
docker network create my-bridge
# You can add after container creation
docker network connect my-bridge my-container
# Or when you create it
docker create --network my-bridge
In user-defined bridge network, containers can talk to each other by using the container names as hostnames.
So if my container was named my-db
with port published at 1234
, then the API would be:
http://my-db:1234
References: