“This is the sixth day of my participation in the August More Text Challenge.

For complex applications, multiple services must be deployed in multiple containers, and there is network communication between services. For example, service A needs to connect to another mysql container.

1. Create a network

Start by creating a new Docker network

Docker network create -d bridge --subnet 172.27.0.0/16 cloud-netCopy the code
  • The -d parameter specifies the Docker network type, including Bridge overlay. Overlay network type is used for Swarm mode.

  • The subnet parameter indicates that a network 172.27.0.0/255.255.0.0 is created. The name of the network is cloud-net.

A network is created to communicate with multiple containers on a host through an Intranet, similar to a software switch.

2. Check the network

You can view all the Docker networks in the current host by running the network ls command

[root@192 ~] docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
02de4daaa2c4        subnet              bridge              local
4764e0697c35        host                host                local
60da7fd0b38e        none                null                local
Copy the code

You can view a list of existing internal networks in the system

It is recommended that containers join a custom Docker network to connect multiple containers instead of using the –link parameter

3. Connect containers

Run a container and connect to the newly created Cloud-net network

Docker run it --rm --network=cloud-net -- IP =172.27.0.20 --name cloud1 cloud-imageCopy the code
  • - the network IP = cloud - net - = 172.27.0.20To fix the IP address of the current container
  • cloud-imageRepresents the image currently in use (replaced with the actual image name)

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

Docker run it --rm --network=cloud-net -- IP =172.27.0.30 --name cloud2 cloud-imageCopy the code

Type the following command in the Cloud1 container to prove that the Cloud1 container and Cloud2 container are interconnected

ping cloud2 
# or ping 172.27.0.30
Copy the code

This allows cloud1 to access the Cloud2 container using IP 172.27.0.30. If the same server is installed in N containers, communication can be realized through the self-built network of Docker

You cannot use 127.0.0.1 connections between containers

4. Schematic diagram of container network

Docker container network diagram can be used to clearly understand the docker network: