Docker container and host access each other

        Recently, when the company installs and deploys projects for customers, because the customer's computer is not connected to any network, the host and the container need to be able to access each other; however, due to the characteristics of the container, both localhost and 127.0.0.1 point to the container in the container internal, not the host machine, so adjustments are required.

        Through a lot of search and practice, I found that the custom network taught on the Internet and the modification of the container to start the specified net network are not very easy to use, and finally found a more convenient method through practice.

        Here we use win10 to test, both Home Edition and Professional Edition are applicable (Linux itself has a network card, you don’t need to use docker’s virtual network card, but using docker’s virtual network card ip is also easy to use).

        First start your docker, then Win + R, enter cmd and press Enter, enter ipconfig on the command line to view ip

        As can be seen from the figure, 192.168.99.1 is the virtual network card ip of docker. The docker started with Docker desktop is the adapter name as shown in the figure. For docker deployed with Docker toolbox, the network card adapter name is VirtualBox.

        Then use the ping command to ping the docker virtual network card address

ping 192.168.99.1

Access success effect:

        Then, enter the docker container to ping the ip address of the network card

#进入容器
docker exec -it <容器ID> /bin/bash

#ping网卡ip地址
ping 192.168.99.1

#若未安装ping命令,使用以下命令进行下载
apt-get update

apt-get install -y inetutils-ping
apt-get install iputils-ping

Ping success effect:

        It can be found that both the host and the container can ping the ip address 192.168.99.1, then we can use this ip address to directly access the host and the container.

The author stepped on the pit: When I was traveling in Du Niang, I found two methods. One is to build a container network network and put the container into this container network. This method can only realize the direct and fast connection between the container and the container. For interaction, if you use the docker virtual network card ip, you can actually access each other, and there is no need to establish a container network.

The second is to expose the container on the host machine, and add --net=host when creating the container, but there is a defect in this startup method, that is, the port cannot be mapped, that is, the command -p 8080:80 cannot be used, which is very easy The port conflict makes the container inaccessible; it is not recommended to use it when deploying in a production environment. When the port conflicts, it is very difficult to detect.

        OK, the above is the content of this sharing, if something is wrong, please correct me~~~///(^v^)\\\~~~

Guess you like

Origin blog.csdn.net/guo0208/article/details/128965734