Joel
Joel

Reputation: 21

Laravel .env config DB_HOST 127.0.0.1 or mysql

After starting a project (Laravel with Docker) according to https://laravel.com/docs/9.x/installation#getting-started-on-windows

There is a problem with DB_HOST in .env: To perform artisan commands like php artisan migrate:fresh DB_HOST need to be set to 127.0.0.1 or localhost which makes sense to me.

But when displaying information on browser (localhost) DB_HOST need to be mysql, otherwise connection is refused.

Why would DB_HOST be set to mysql at all? How could I solve it so DB_HOST work for both cases?

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1 || localhost || mysql(?)
DB_PORT=3306
B_DATABASE=tutorial
DB_USERNAME=sail
DB_PASSWORD=password

Database

'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', ''),
            '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'),
            ]) : [],
        ],

Upvotes: 1

Views: 1356

Answers (2)

rick
rick

Reputation: 1

had the same issue, here's the fix:

If you're doing this laravel + docker setup using laravel sail , do not run commands as php artisan but instead as sail artisan, and keep your hostname as the default, in this case it would be mysql

Upvotes: 0

Pau
Pau

Reputation: 41

For me, the solution was to find the docker IP with:

dd(Request::ip());    

That was not 127.0.0.1 but 172.18.0.1. After that I configured .ENV file with:

DB_HOST=172.18.0.1

And run

php artisan migrate:refresh

from docker terminal(and NOT from local) and everything works OK

Unfortunately, I don't know how to explain why, I hope someone else can shed a little more light on the matter

Upvotes: 1

Related Questions