Access to mysql container from other container

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


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");

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.


If you are using docker-compose, than the database will be accessible under the service name.

version: "3.9"
services:
  web:
    build: .
    ports:
      - "8000:8000"
  db:
    image: postgres
    ports:
      - "8001:5432"

Then the database is accessible using: postgres://db:5432. Here the service name is at the same time the hostname in the internal network.

Quote from docker docs:

When you run docker-compose up, the following happens:

  1. A network called myapp_default is created.
  2. A container is created using web’s configuration. It joins the network myapp_default under the name web.
  3. A container is created using db’s configuration. It joins the network myapp_default under the name db.

Source: https://docs.docker.com/compose/networking/

Tags:

Docker

Mysql