Home >Database >Mysql Tutorial >How to Securely Connect to a MySQL Container from Another Container in Docker?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 10:16:291075browse

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:

  • Host Name Resolution: Each container on the network can communicate using container names as hostnames.
  • Network Isolation: By default, containers on different networks are isolated and cannot communicate.
  • Security: Custom networks allow for granular access control and isolation, reducing potential security vulnerabilities.

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!

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