Pietro Bongiovanni
Pietro Bongiovanni

Reputation: 554

MYSQLI Connection refused when connecting to another docker container running MariaDB

I'm starting to get my hands dirty with Docker and I'm trying to get my PHP application running in a docker container with nginx to connect to the database running in another container running MariaDB.

When I run the containers, I can connect without any problems to the database from my computer (using Sequel Pro) but when i try to connect to the database from the PHP application running in the nginx container I get the following mysqli error:

Warning: mysqli_connect(): (HY000/2002): Connection refused in >/app/web/php/db-config.php on line 7 Failed to connect to the database, died with error:

The db-config.php where the error happens is as follows:

    define('DB_HOST', '0.0.0.0:3306');
    define('DB_NAME', 'Jumpooling');
    define('DB_USER', 'root');
    define('DB_PASSWORD', 'root');

    $con=mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die('Failed to connect to the database, died with error:');

All the docker-compose.yml file content is in this repository.

What am I missing?

Upvotes: 5

Views: 9553

Answers (3)

Matteus Barbosa
Matteus Barbosa

Reputation: 2725

You should specify the ports container/browser explicitly as -p 3306:3306:

docker run --name mysql-container -p 3306:3306 -e MYSQL_ROOT_PASSWORD=secret -d mysql:latest

Upvotes: 0

user634545
user634545

Reputation: 9419

Links are not required to enable services to communicate - by default, any service can reach any other service at that service’s name.

Containers for the linked service will be reachable at a hostname identical to the alias, or the service name if no alias was specified.

Upvotes: 0

Pietro Bongiovanni
Pietro Bongiovanni

Reputation: 554

I managed to find the solution in this answer.

The problem was that the host was not to be defined as an IP address but with the link name that it is given in the docker-compose.yml file, that is db.

The final db-config.php is, thus:

define('DB_HOST', 'db');
define('DB_NAME', 'Jumpooling');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');

$con=mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, 3306) or die('Failed to connect to the database, died with error:');

Upvotes: 35

Related Questions