"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Connect to a MySQL Container from Another Container in Docker?

How to Connect to a MySQL Container from Another Container in Docker?

Published on 2024-11-08
Browse:973

How to Connect to a MySQL Container from Another Container in Docker?

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3