[SOLVED] Access to mysql container from other container

Issue

I have setup docker container with mysql that expose 3306.
I’ve specified database user, database password and create a test db and give the privileges to new user.
In another container i want to accesso to this db.
So i set up new container with a simply php script that create new table in this db.
I know that mysql container’s ip is 172.17.0.2 so :

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

Than using mysqli i create new table and all works fine.
But i think that connect to container using his ip address is not good.
Is there another way to specify db host? I tryed with the hostname of the mysql container but it doens’t work.

Solution

You need to link your docker containers together with –link flag in docker run command or using link feature in docker-compose. For instance:

docker run -d -name app-container-name --link mysql-container-name app-image-name

In this way docker will add the IP address of the mysql container into /etc/hosts file of your application container.
For a complete document refer to:
MySQL Docker Containers: Understanding the basics

Answered By – sara

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.