以下のエラーが出たので、いろいろ調べたら単にDBに接続していないだけでした。
$ php artisan migrate
Illuminate\Database\QueryException
SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known (SQL: select * from information_schema.tables where table_schema = app 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▕ }
+33 vendor frames
34 artisan:37
Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
とはいえ、phpmyadminからは正しく接続できていて、なんでmigrationするとエラーになるので結局LaravelからDBに接続できないというだけのようです。
まずはDBの設定を確認してみます。Docker環境なのでBuild時のパラメーターをdocker-compose.ymlで確認します。
...
mysql:
image: 'mysql:8.0'
ports:
- '${FORWARD_DB_PORT:-3306}:3306'
environment:
MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
MYSQL_DATABASE: '${DB_DATABASE}'
MYSQL_USER: '${DB_USERNAME}'
MYSQL_PASSWORD: '${DB_PASSWORD}'
MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
volumes:
- 'sailmysql:/var/lib/mysql'
networks:
- sail
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-p${DB_PASSWORD}"]
retries: 3
timeout: 5s
...
環境変数から設定することになっているので.env
の設定を確認します。
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=app
DB_USERNAME=sail
DB_PASSWORD=password
Laravelがデフォルトで設定してくれるものなので、問題ないです。
tinkerで確認しても設定に問題無い感じです。
$ php artisan tinker
Psy Shell v0.10.8 (PHP 7.3.25 — cli) by Justin Hileman
>>> DB::connection()->getConfig();
=> [
"driver" => "mysql",
"host" => "mysql",
"port" => "3306",
"database" => "app",
"username" => "sail",
"password" => "password",
"unix_socket" => "",
"charset" => "utf8mb4",
"collation" => "utf8mb4_unicode_ci",
"prefix" => "",
"prefix_indexes" => true,
"strict" => true,
"engine" => null,
"options" => [],
"name" => "mysql",
]
>>>
composerのアップデートやartisanのオプティマイズをやっても状況は同じ。
dockerではこんなのもやってみる。
$ docker-compose down
$ docker-compose build --no-cache mysql
仕方がないのでdockerにログインしてmysqlに接続してみる。
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
こういうときはDockerの再起動。
$ docker-compose restart
以上です。
2021.8.1 (日)