Search code examples
phpmysqllaraveldockerlaravel-sail

Laravel Sail - SQLSTATE[HY000] [2002] No such file or directory


I followed the tutorial of Laravel Sail and it is working fine, but if I clone the repo (docker-compose up), in another machine, I get the following error when trying to run migrations inside the container:

SQLSTATE[HY000] [2002] No such file or directory (SQL: create table migrations (id int unsigned not null auto_increment primary key, migration varchar(255) not null, batch int not null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')

Already tried some solutions but nothing worked.

My database.php file:

'mysql' => [
        'driver' => 'mysql',
        'url' => env('DATABASE_URL'),
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', '/var/run/mysqld/mysqld.sock'),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'prefix_indexes' => true,
        'strict' => true,
        'engine' => null,
        'options' => extension_loaded('pdo_mysql') ? array_filter([
            PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
        ]) : [],
    ],

My .env file:

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=code_challenge
DB_USERNAME=root
DB_PASSWORD=

Solution

  • Because you are trying to connect to DB container via socket from different container.

    There are two separate containers - Laravel and MySQL. Thinks of it like two separate servers.

    When you have both unix_socket and db_host in env, you are telling laravel to connect to db at specified host via unix_socket. That is why it didn't work.

    When you update the unix_socket env, laravel try to connect to DB via TCP and it work.

    P.S: I know this issue is already resolved for you. But in case someone else stumble upon this question, they should have some explanation on why it work and how to fix it in the future.