'Error connecting to database through Docker

I have a mysql service running on port 3308 using docker. However on table plus when I try to access this using “127.0.0.1” as the Host and Port “3308”, enter the user, password and database name if I test the connection it shows an error:

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

Also If I run php artisan migrate I get:

 Illuminate\Database\QueryException

  SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO) (SQL: select * from information_schema.tables where table_schema = project and table_name = migrations and table_type = 'BASE TABLE')

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:712
    708▕         // If an exception occurs when attempting to run a query, we'll format the error
    709▕         // message to include the bindings with SQL, which will make this exception a
    710▕         // lot more helpful to the developer instead of just the database's errors.
    711▕         catch (Exception $e) {
  ➜ 712▕             throw new QueryException(
    713▕                 $query, $this->prepareBindings($bindings), $e
    714▕             );
    715▕         }
    716▕     }

If I use the port 3306 on tableplus I can connect to the database but still get the issue with the php artisan command. But it's strange because in docker is configured with port 3308.

The .env file is like this:

DB_CONNECTION=mysql
DB_HOST=host.docker.internal
DB_PORT=3308
DB_DATABASE=project
DB_USERNAME=root
DB_PASSWORD=pass

Do you know what can be the issue?



Solution 1:[1]

Are both container, php-fpm and the database-service-container, in the same network? Did you change the database config in .env? The config parameter DB_HOST should not show an ip, instead set it to the name of your mysql container/Service. Eg.G DB_HOST=database

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 C4pt4inC4nn4bis