Home > Database > Mysql Tutorial > body text

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

Susan Sarandon
Release: 2024-10-28 00:20:02
Original
995 people have browsed it

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
Copy after login

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
Copy after login

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");
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template