How docker implements cross-network access between containers

1. docker network

1. Overview of docker network

Docker has a virtual route docker0 by default. The network mode of docker0 is bridge mode. Docker containers are forwarded through this virtual route between hosts, which is equivalent to a LAN; when creating a container, docker will create a virtual network card for each container. .

2. Common network modes of docker

bridge: bridge mode
none: do not specify the network
host: shared host network
container: container network

3. Common commands for docker network

docker network --help

2. How docker implements cross-network access between containers

1. View all docker networks

docker network ls

2. Create a different network to simulate the network of different network segments in the container (custom subnet mask and gateway)

docker network create --driver bridge --subnet 192.168.1.0/16 --gateway 192.168.1.0 diffnet

3. Start two tomcats with docker0 and diffnet
 

4. View tomcat container information under different networks

docker network inspect diffnet   # diffnet 替换成对应的network id或name

Corresponding container IP under docker0 network:

        docker-tomcat01:172.17.0.4

        docker-tomcat02:172.17.0.5

Corresponding container IP under diffnet network:

        diffnet-tomcat01:192.168.0.1

        diffnet-tomcat02:192.168.0.2

5. Install the ping command in the container

After entering the container, if the ping command cannot be used, use the following command to install inside the container.

apt-get update
apt install net-tools       
apt install iputils-ping 

If the internal installation fails, you can use the following method to install using the ping command

1.在宿主机上使用以下命令手动下载 BusyBox:
wget https://busybox.net/downloads/binaries/1.21.1/busybox-x86_64
2.然后将下载的文件复制到容器内:
docker cp busybox-x86_64 <容器名称或ID>:/usr/local/bin/busybox
3.在容器内创建符号链接并安装 ping 命令:
docker exec -it <容器名称或ID> ln -s /usr/local/bin/busybox /bin/ping
4.给下载的文件授予执行权限:
chmod +x /usr/local/bin/busybox   #容器内执行

6. Use the ping command within the container to check connectivity.

The check results are as follows: The pings on the same network can be successful, but the pings on other network segments cannot be successful.

7. Connect the container in docker0 to the diffnet network

docker network connect diffnet docker-tomcat01

View diffnet information through commands

 docker network inspect diffnet

Docker-tomcat01 is added to the metadata of diffnet through the connect command.

Re-enter the container docker-tomcat01 and conduct a ping command connectivity test on different networks. The results are as follows:

As a result, the cross-network access function between docker containers has been realized.

Guess you like

Origin blog.csdn.net/qq_54494363/article/details/132601636