Connecting to a MySQL Container from Another Container
You've set up a Docker container running MySQL and exposed port 3306, but how can you access that database from another container?
Using IP Address
Initially, you tried connecting using the MySQL container's IP address (172.17.0.2). While this works, it's not ideal as IP addresses can change.
User-Defined Networks
A better approach is to use user-defined networks to connect containers. You can create a network and attach both the MySQL and PHP containers to it.
docker network create my_network
Linking Containers
Run both containers on the same network, providing the network name using the --network flag:
docker run -d --name php_container --network my_network my_php_image docker run -d --name mysql_container --network my_network my_mysql_image
Within the containers on that network, you can resolve container names and connect using the hostname. For example, from the PHP container, you could connect to MySQL using:
$mysqli = new mysqli("mysql_container", "mattia", "prova", "prova");
Conclusion
User-defined networks provide a more robust and flexible way to connect containers in Docker. Using container names as hostnames simplifies access and eliminates the need to rely on IP addresses.
The above is the detailed content of How to Connect to a MySQL Container from Another Container in Docker?. For more information, please follow other related articles on the PHP Chinese website!