サイトアイコン 演劇とかの感想文ブログ

[PHP]Laravel Sailで、SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failedが出たときの対処

PHPのフレームワーク、Laravelを勉強中です。現在は、「PHPフレームワーク Laravel Webアプリケーション開発 バージョン8.x対応」を読んで勉強してます。その中で、Migrateコマンド実行時に、表題のエラーに悩まされました

目次

結論 Dockerに入らずに実行していた

この本で記載されている手順に従い、sailで環境を構築していたのですが、本の中に記載されているコマンドをそのまま実行すると上記のエラーがでます。

$ php artisan migrate

これを実行すると、以下のエラーが出ます

SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known (SQL: select * from information_schema.tables where table_schema = sample and table_name = migrations and 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▕

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

で、これを

$ sail artisan migrate

とすると以下のようにうまく実行できました

Migrating: 2021_06_28_012332_create_authors_table
Migrated: 2021_06_28_012332_create_authors_table (162.47ms)
Migrating: 2021_06_28_034753_create_publishers_table
Migrated: 2021_06_28_034753_create_publishers_table (84.57ms)
Migrating: 2021_06_28_035130_create_books_table
Migrated: 2021_06_28_035130_create_books_table (90.40ms)
Migrating: 2021_06_28_035507_create_bookdetails_table
Migrated: 2021_06_28_035507_create_bookdetails_table (87.47ms)

phpとsailの違い

要は、sailで環境を作ったら、php artisanはDockerの中で実行しないといけないようです。そして、そのコマンドがsail
以下のリンク先の質問で理由に気づけました。

I'm having a problem with laravel sail, it happens that I just cloned the repository and it is unchanged, the docker-compose.yml is totally intact, however, after executing ./vendor/bin/sail up I h...
Error with LARAVEL SAIL [php_network_getaddresses: getaddrinfo failed] - Stack Overflow

疑うべきは、.envとdocker_composer.xml

ちなみに、エラーメッセージで検索すると以下のページがヒットします。

DockerでPHPエラー「php_network_getaddresses: getaddrinfo failed: Name or service not known」 DockerでLAMP環境を構築し、Laravelをインストールしたところ、タイトルに書いてある「php_network_getaddresses: getaddrinfo failed: Name or service not known」というエラーが発生しました。どうやらDB接続でこけている様子。今回はこのエラーについて調査した結果をまとめます。 エラーの内容調査 エラー内容を読むと「getaddrinfo failed」ということで、アドレス情報取得時のエラーであることが分かります。 似たようなエラー...
DockerでPHPエラー「php_network_getaddresses: getaddrinfo failed: Name or serv... - TECH Projin(テックプロジン)

本来は、.envとdocker_composer.xmlでDB_CONNECTの値に不整合がある場合に発生するエラーのようです

ただ、僕の場合、localhostでつないだ場合に、DBに接続できているようだったので、この不整合はないのではないかと考えて、更に検索を繰り返して、ようやく問題解決に至りました。

php artisanでもうまくいく場合とそうでない場合

phpのファイルを作成する系のartisanは、php artisan~でもうまくいきます。例えば

php artisan make:migration ファイル名
php artisan make:seeder ファイル名

しかし、以下のようなDBにアクセスする系のコマンドはsailでないとうまくいきません

sail artisan migrate
sail artisan db:seed

モバイルバージョンを終了