Docker containers connect to communicate with each other

Port mapping is not the only way to connect a Docker to another container.

Docker has a connection system that allows multiple containers to connect together and share connection information.

A Docker connection creates a parent-child relationship where the parent container can see the child’s information.

When we create a container, Docker automatically names it. Alternatively, we can use the –name identifier to name the container, for example:

runoob@runoob:~$  docker run -d -P --name runoob training/webapp python app.py
43780a6eabaaf14e590b6e849235c75f3012995403f97749775e38436db9a441
Copy the code

We can use the docker ps command to view the container name.

runoob@runoob:~$ docker ps -l
CONTAINER ID     IMAGE            COMMAND           ...    PORTS                     NAMES
43780a6eabaa     training/webapp   "python app.py". 0.0.0.0:32769 - > 5000 / TCP runoobCopy the code

Create a new Docker network.

$ docker network create -d bridge test-net
Copy the code



Parameter Description:

-d: Specifies the Docker network type, including bridge and overlay.

The overlay network type is used in Swarm mode, which you can ignore in this section.

Connect container Run a container and connect to the new test-net network:

$ docker run -itd --name test1 --network test-net ubuntu /bin/bash
Copy the code

Open a new terminal, run another container and join the test-net network:

$ docker run -itd --name test2 --network test-net ubuntu /bin/bash
Copy the code



Test1 and test2 are connected by ping.

If no ping command is used to ping test1 or test2, run the following command to ping the test1 or test2 containers.

apt-get update
apt install iputils-ping
Copy the code

Enter the following command in the test1 container:

Click on the image to see a larger version: