Wednesday, February 2, 2022

[FIXED] Can`t connect to mysql database in cakephp in a local environment with docker

Issue

I set up an local enviroment with mysql, phpmyadmin, php and mailhog and I`m not able to connect to the database with CakePhp.

My connection data in config/app.php:

'default' => [
          'className' => 'Cake\Database\Connection',
        'driver' => 'Cake\Database\Driver\Mysql',
        'persistent' => false,
        'host' => '172.21.0.4', => I tried localhost, mysql, 172.0.0.1 as well...
        'username' => 'root',
        'password' => 'root',
        'database' => 'mydb1',
        'encoding' => 'utf8mb4',
        'timezone' => 'UTC',
        'cacheMetadata' => true,
        'flags' => [],
        'log' => false,

The error I get when I go to http://localhost/

When I test the connection via mysqli_connect() (directly in config/app.php), it`s working fine:

$link = mysqli_connect("mysql", "root", "root",'mydb1',"3306",'');

if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}

echo "Success: A proper connection to MySQL was made!" . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;

$query = "SELECT * FROM test";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
$flag = FALSE;

while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) 
{
    echo $row['test']."<br>";
}

mysqli_close($link);

Thank you very much! Regards from Austria!


Solution

First, make sure you are not using the app_local.php configuration file.

If you use docker, then use the same name for the host as for db service

Docker Compose

services:
      db:
        platform: linux/x86_64
        image: mysql:5.7

app.php

'Datasources' => [
    'default' => [
        'host' => 'db', //<------------------


Answered By - Salines

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.