Home >Database >Mysql Tutorial >How to Securely Connect to a MySQL Container from Another Container in Docker?
Accessing MySQL Container from Another Container
In a dockerized environment, connecting to a database hosted in a separate container can pose a challenge. While using the container's IP address for database connectivity may seem straightforward, it introduces potential risks and limitations.
Fortunately, Docker provides a more robust solution through user-defined networks. By creating a network and connecting both the MySQL and client containers to it, you can establish reliable and secure communication between them.
Step 1: Create a Network
Run the following command to create a custom network named "my_network":
docker network create my_network
Step 2: Start the MySQL Container
Start the MySQL container within the created network:
docker run -d --name mysql_container --network my_network my_mysql_image
Step 3: Start the Client Container
Similarly, start the client container on the same network:
docker run -d --name php_container --network my_network my_php_image
Step 4: Database Connectivity Script
Within the client container, you can establish database connectivity using the hostname of the MySQL container:
<code class="php">$mysqli = new mysqli("mysql_container", "mattia", "prova", "prova");</code>
Benefits of Using User-Defined Networks
Utilizing user-defined networks provides several advantages:
The above is the detailed content of How to Securely Connect to a MySQL Container from Another Container in Docker?. For more information, please follow other related articles on the PHP Chinese website!