Home  >  Article  >  Database  >  How to Reliably Connect to a MySQL Container from Another Container?

How to Reliably Connect to a MySQL Container from Another Container?

DDD
DDDOriginal
2024-10-25 15:41:02984browse

How to Reliably Connect to a MySQL Container from Another Container?

Connecting to MySQL Container from Another Container

Maintaining a connection between containers can be essential in distributed systems. When working with MySQL containers, accessing the database from another container is crucial.

Problem Statement:

You have created a MySQL container exposing port 3306. Within another container, you're attempting to access this database using its IP address. However, you feel this method is unreliable and are looking for alternative host specification options.

Solution:

The legacy --link flag used to connect containers is now considered outdated. Instead, user-defined networks are recommended.

To connect both containers on the same 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

Mechanism:

By placing both containers on the same user-defined network ("my_network" in this example), each container can communicate with the other using the assigned container name as the hostname.

For example, to access the MySQL container in the PHP container using mysqli, you would specify:

$mysqli = new mysqli("mysql_container", "mattia", "prova", "prova");

The above is the detailed content of How to Reliably Connect to a MySQL Container from Another Container?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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