【Laravel7】docker環境でDBが「Connection refused」
dockerでlaravelの環境構築を行ったのですがデータベースにつながらなかったので解決方法を探していきます。
使用した環境
- Mac OS Catalina -10.15.7
- PHP -7.2.34
- Laravel -7.28.4
- Composer -2.0.3
- Docker -19.03.13
実際に出現したエラー
Laravelでphp artisan migrate
を行うと以下のようなエラーが出ました。
$ php artisan migrate
Illuminate\Database\QueryException
SQLSTATE[HY000] [2002] Connection refused (SQL: select * from information_schema.tables where table_schema = sample1 and table_name = migrations and table_type = 'BASE TABLE')
at vendor/laravel/framework/src/Illuminate/Database/Connection.php:671
667| // If an exception occurs when attempting to run a query, we'll format the error
668| // message to include the bindings with SQL, which will make this exception a
669| // lot more helpful to the developer instead of just the database's errors.
670| catch (Exception $e) {
> 671| throw new QueryException(
672| $query, $this->prepareBindings($bindings), $e
673| );
674| }
675|
+37 vendor frames
38 artisan:37
Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
おそらくdocker-compose.yml
に記述されたmysqlの設定とlaravelの.env
に記述されたmysqlの設定が合っていないのが原因だと考えられます。
解決方法
まずはdocker-compose.yml
を確認します。
mysql:
image: mysql:5.7
environment:
MYSQL_DATABASE: darabase_name
MYSQL_USER: user_name
MYSQL_PASSWORD: password
MYSQL_ROOT_PASSWORD: password
ports:
- "3306:3306"
volumes:
- mysql-data:/var/lib/mysql
続いて.env
を確認し、上記の記述と揃えます。
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=user_name
DB_PASSWORD=password
編集が終わった後、コンテナを再起動して、再びmigrateします.
$ docker-compose down
$ docker-compose up -d
$ docker-compose exec app bash
## cd laravel
## php artisan migrate
うまくいきました。
# php artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table (0.09 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table (0.05 seconds)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated: 2019_08_19_000000_create_failed_jobs_table (0.03 seconds)