In a Docker environment, you may encounter the need to connect to a MySQL container from another container. While it's possible to establish a connection using the MySQL container's IP address, this approach lacks flexibility. To improve accessibility, alternative methods exist.
One recommended solution is to utilize user-defined networks. This method offers several benefits over the legacy --link flag:
To utilize user-defined networks, follow these steps:
docker network create my_network
docker run -d --name php_container --network my_network my_php_image docker run -d --name mysql_container --network my_network my_mysql_image
Once the containers are running on the same network, they can communicate using each other's container names as hostnames. In this scenario, the PHP container can establish a connection to the MySQL container using the following code:
<code class="php">$mysqli = new mysqli("mysql_container", "mattia", "prova", "prova");</code>
By leveraging user-defined networks, you can achieve seamless container-to-container communication without relying on IP addresses, improving flexibility and simplifying configuration in your Docker environment.
The above is the detailed content of How to Access a MySQL Container from Other Containers in Docker Without IP Addresses?. For more information, please follow other related articles on the PHP Chinese website!