Search code examples
mysqldockerlaravel-8laravel-artisanwindows-subsystem-for-linux

(Docker) Laravel and Artisan Commands .env DB_HOST Conflict


I am running a Docker container group for a Laravel app on a Windows 10 machine and accessing them through my Windows browser (http://localhost), as well as through my Ubuntu WSL shell. The relevant containers are laravel (port 80) and mysql (port 3306) - so standard port configuration.

I have a strange issue where changing the DB_HOST variable in my Laravel .env file enables some functionality and produces errors for other functionality. For instance, if the DB_HOST value in the .env file is 127.0.0.1, I can successfully run artisan commands in my WSL shell that interact with the mysql database (such as migrations), but I cannot access my Laravel website through my host browser, i.e. in the browser I get:

Illuminate\Database\QueryException
SQLSTATE[HY000] [2002] Connection refused (SQL: select * from `posts`)

If I change the DB_HOST value to be the mysql container's IP address or name, I can see my website from the host browser, but I can't run the artisan commands that interact with the database (such as migrations/seeding). For instance, the following command:

php artisan migrate:fresh --seed

produces the following error:

 Illuminate\Database\QueryException

  SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No address associated with hostname (SQL: SHOW FULL TABLES WHERE table_type = 'BASE TABLE')

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:692
    688▕         // If an exception occurs when attempting to run a query, we'll format the error
    689▕         // message to include the bindings with SQL, which will make this exception a
    690▕         // lot more helpful to the developer instead of just the database's errors.
    691▕         catch (Exception $e) {
  ➜ 692▕             throw new QueryException(
    693▕                 $query, $this->prepareBindings($bindings), $e
    694▕             );
    695▕         }
    696▕

      +44 vendor frames
  45  artisan:37
      Illuminate\Foundation\Console\Kernel::handle()

Clearly the Laravel container is having difficulty establishing a connection to the mysql container consistently in both of these contexts. What value do I need to insert within the DB_HOST variable so that I can perform both of these types of operations without DB connection issues?


Solution

  • For anyone that may run across this issue, a year and a half later I finally figured it out. The DB_HOST value should be your host device's internal IP address.