How to Connect to the Host Machine's MySQL Server from Inside a Docker Container
The blogger recently encountered a situation where they copied a database from a server onto the host machine’s MySQL server, wanting to use the local database to test the correctness of their code. However, the project programs are all deployed with a single click via Docker, so it’s necessary to access the local database from within the Docker container. During the exploration, they encountered problems and found solutions.
In a Docker Container, localhost Does Not Refer to the Host Machine’s localhost
For this reason, you cannot access the host machine’s MySQL by using localhost:3306 inside the container.
Docker Creates a Virtual Network Interface When Running, Named docker0
We can run ifconfig on the host machine to see it. This is the bridge established by the host machine for communication with various containers.
The Host Machine’s IP Address in the Same LAN as the Container is Generally the First Address of the IP Address Range Corresponding to docker0 (e.g., 172.0.17.1)
We can access the host machine’s MySQL server by using 172.0.17.1:3306 from within the container.
The Default MySQL Server Setting Allows Access Only from IP Addresses in the 127.0.0.1 Segment
So at this point, using 172.0.17.1:3306 still cannot access the host machine. At this point, you need to configure MySQL further.
mysql>GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '123456' WITH GRANT OPTION;
mysql>flush privileges;
// 其中各字符的含义:
// *.* 对任意数据库任意表有效
// "root" "123456" 是数据库用户名和密码
// '%' 允许访问数据库的IP地址,%意思是任意IP,也可以指定IP
// flush privileges 刷新权限信息