Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to mysql container from other container

Tags:

docker

mysql

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.

like image 951
Isky Avatar asked Feb 16 '16 10:02

Isky


People also ask

How do you call a container from another container?

For containers to communicate with other, they need to be part of the same “network”. Docker creates a virtual network called bridge by default, and connects your containers to it. In the network, containers are assigned an IP address, which they can use to address each other.


3 Answers

The --link flag is considered a legacy feature, you should use user-defined networks.

You can run 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 

Every container on that network will be able to communicate with each other using the container name as hostname.

like image 96
Tiago C Avatar answered Sep 20 '22 04:09

Tiago C


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

like image 34
sara Avatar answered Sep 20 '22 04:09

sara


In your docker-compose.yml file add a link property to your webserver service: https://docs.docker.com/compose/networking/#links

Then in your query string, the host parameter's value is your database service name:

$mysqli = new mysqli("database", "mattia", "prova", "prova");
like image 38
TvC Avatar answered Sep 19 '22 04:09

TvC