見出し画像

Docker Laravelでマイグレーション実行時にエラーとなった時はTinkerを使ってデバッグする

Laravelをインストールし、マイグレーションファイルを作って実行しようとしたら、エラーになって解決方法に悩みました。

$ php artisan migrate

SQLSTATE[HY000] [2002] Connection refused

スクリーンショット 2019-12-30 18.39.38

⚠エラーメッセージ

   Illuminate\Database\QueryException  : SQLSTATE[HY000] [2002] Connection refused (SQL: select * from information_schema.tables where table_schema = todo-list and table_name = migrations and table_type = 'BASE TABLE')
 at /opt/src/app/vendor/laravel/framework/src/Illuminate/Database/Connection.php:665
   661|         // If an exception occurs when attempting to run a query, we'll format the error
   662|         // message to include the bindings with SQL, which will make this exception a
   663|         // lot more helpful to the developer instead of just the database's errors.
   664|         catch (Exception $e) {
 > 665|             throw new QueryException(
   666|                 $query, $this->prepareBindings($bindings), $e
   667|             );
   668|         }
   669|
 Exception trace:
 1   PDOException::("SQLSTATE[HY000] [2002] Connection refused")
     /opt/src/app/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70
 2   PDO::__construct("mysql:host=127.0.0.1;port=3306;dbname=todo-list", "docker", "secret", [])
     /opt/src/app/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70
 Please use the argument -v to see more details.

設定がうまくいっていないようです。

tinkerコマンドで現在どのようにMySQLへ接続しているのか確認してみます!

$ php artisan tinker

このようにTinker環境に入って設定をみる事ができます。

スクリーンショット 2019-12-30 18.55.49

hostが127.0.0.1になっています。

これは自身のIPで、Dockerで環境構築している場合、Laravelが動いているコンテナと、MySQLが動いているコンテナが違うので、同じIPだとLaravel自身のIPをみにいってしまうので、MySQLへの接続がうまくいっていないということらしいです・・。

これは、hostの設定を変える事で解決します。

Laravelの.envファイルに下記を追記します。(.envファイルがなければ、.env.exampleからcpします)

DB_HOST=mysql

これで、先ほどのTinkerで再度確認します。

スクリーンショット 2019-12-30 19.04.11

hostがmysqlになりました。

これでもう一度マイグレーションファイルを実行

$ php artisan migrate

スクリーンショット 2019-12-30 19.04.41

無事に実行できました! 🎉


スキ頂けると嬉しいです〜