Two containers can communicate with each other when they are in same network. Below are the steps to achieve the communication between containers in a network.
- Create and View network.
- Create nginx image.
- Run the image created in step 2 as container mynginx1 with user defined network created in step 1.
- Verify that container is running.
- Run the image created in step 2 as container mynginx2 with user defined network created in step 1.
- Verify that container is running.
- Access each container using curl.
- Verify each container attached to user defined network.
- Go into the container mynginx1. Ping to the mynginx2.
- Go into the container mynginx2. Ping to the mynginx1.
- Getting logs of each of the container.
- Remove resources.
- Stop the both of the containers.
- Remove the images.
- Remove the network.
- create:
sudo docker network create --driver bridge my_nw - view:
sudo docker network ls
-
Download this repository. Go to the repostiroy directory. Open the terminal.
-
create image:
sudo docker build -t my-nginx-image .
You will see below screen while running the above command.
Imgae create successfully

- run :
sudo docker run --rm --name mynginx1 --network="my-nw" -d -p 81:80 my-nginx-image - view:
sudo docker ps - mynginx1 is exposed to 81 port of the localhost.
- run :
sudo docker run --rm --name mynginx2 --network="my-nw" -d -p 82:80 my-nginx-image - view:
sudo docker ps - mynginx2 is exposed to 82 port of the localhost.

- inspect mynginx1 container :
sudo docker container inspect mynginx1
- inspect mynginx2 container :
sudo docker container inspect mynginx2
For both of the containers you can see the network name is my-nw.
sudo docker exec -it mynginx1 bash
- Access mynginx2 from container mynginx1. See I am using container name instead container's ip.
curl http://mynginx2:80
- validate if ping is working or not. Ping will show the network name as
my-nw.ping mynginx2
- exit from the container
mynginx1.exit
- Screenshots for this use case is similar to above. So I am not attaching again.
sudo docker exec -it mynginx2 bash- Access mynginx1 from container mynginx2. See I am using container name instead container's ip.
curl http://mynginx1:80 - validate if ping is working or not.
ping mynginx2 - exit from the container
mynginx1.exit
-
stop containers:
sudo docker stop mynginx1 mynginx2. This will stop and remove the containers as we have started the containers with --rm flag. verify if containers are removed or not:sudo docker psand thensudo docker ps -a.
We are seeing some old containers but not the containers mynginx1 and mynginx2. -
delete image:
sudo docker rmi my-nginx-image. Verify if image is deleted or not.sudo docker images.
After delete. we are not seeing our image my-nginx-image. -
delete network:
sudo docker network rm my-nw. Verify if network is deleted or not.sudo docker network ls. After delete, we wont able to see the network my-nw.
Practice again from the beggining of this document.




