Docker Networking

Docker networking allows containers to communicate with each other, the host machine, and external networks. It provides several network drivers like bridge, host, and overlay to manage container connectivity in different environments.
If we create a container named nginx1
and another named nginx2
, they will be able to communicate with each other if they are on the same Docker network. Docker uses container names as DNS hostnames within the same network, allowing easy inter-container communication.
sudo docker run -d -rm —name nginx1 nginx sudo docker run -d -rm —name nginx2 nginx
Note: --rm
deletes the container after it stops
To ping from nginx1
to nginx2
:
sudo docker exec -it nginx1 /bin/bash apt update && apt install iputils-ping -y ping nginx2
Here Bridge is working as a virtual switch when two docker container communicate with each other.
In this setup, the problem is that if we have more containers, all of them can communicate with each other, but this should not happen—only specific containers should be allowed to communicate based on security or application boundaries.
To resolve this, we create a custom bridge network:
sudo docker network create —driver bridge demo_network
To see the list of all the Docker network:
sudo docker network ls
Now, run two containers in the same custom network:
sudo docker run -d -rm --name my_nginx --network demo_network nginx sudo docker run -d -rm --name my_redis --network demo_network redis
To ping from my_nginx
to my_redis
:
sudo docker exec -it my_nginx /bin/bash apt update && apt install iputils-ping -y ping my_redis
Note: You can also ping using the container’s IP, but using the container name is preferred as Docker handles name resolution.
Now let’s create another container not in the same network:
sudo docker -d -rm --name outer_nginx nginx
Try to ping my_nginx
from outer_nginx
:
sudo docker exec it outer_nginx /bin/bash
apt update && apt install iputils-ping -y
ping my_nginx
You will see that outer_nginx
cannot ping my_nginx
because they are in different networks, and Docker isolates containers across different bridge networks by default.
Subscribe to my newsletter
Read articles from Amit Jajoo directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
