Lavavel(8.x) sailでMySQLコンテナ起動・マイグレーション
MySQLコンテナ起動
.env の DB_USERNAME を root 以外の任意の文字列、DB_PASSWORDは任意の文字列に設定
docker-compose.yml の環境設定(environment, パスワードは MYSQL_PASSWORD のみにする
DBのマイグレーションファイル作成
laravelコンテナ(今回はlaravel.test)に入り、ルートディレクトリでマイグレーション実行
code: linux
% docker-compose exec laravel.test bash
root@xxxxxxx:/var/www/html# php artisan make:migration create_flights_table
Created Migration: 2021_07_05_135544_create_flights_table
mysqlコンテナに入ってDBの確認→空っぽ。。
code: linux
% docker-compose exec mysql bash
root@xxxxxxxx:/# mysql -u root -h localhost -p // rootユーザではなく.envで指定したユーザだと入れず...
Enter password: // .envで指定したパスワード入力
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 8.0.25 MySQL Community Server - GPL
// ログ中略
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| example_app |
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
5 rows in set (0.02 sec)
mysql> use example_app;
Database changed
mysql> show tables;
Empty set (0.01 sec)
DBのマイグレーション
マイグレーションでエラー発生
code: linux
root@xxxxxx:/var/www/html# php artisan migrate
Illuminate\Database\QueryException
SQLSTATEHY000 2002 Connection refused (SQL: select * from information_schema.tables where table_schema = example_app and table_name = migrations and table_type = 'BASE TABLE') at vendor/laravel/framework/src/Illuminate/Database/Connection.php:678
.envの DB_HOST をDockerコンテナ名に書き換え
code: env
# DB_HOST=127.0.0.1
DB_HOST=mysql
DB_USERNAME を任意のユーザ名→ root にしたらマイグレーション成功
code: linux
root@xxxxxxx:/var/www/html# php artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
...
DBのカラム確認
code: linux
mysql> select column_name from information_schema.columns where table_schema = 'example_app' and table_name = 'flights';
+-------------+
| COLUMN_NAME |
+-------------+
| id |
| name |
| airline |
| created_at |
| updated_at |
+-------------+
5 rows in set (0.00 sec)
マイグレーションファイル 利用可能なカラムタイプ
dockerのmysqlコンテナ初回起動時のエラー
code: linux
mysql_1 | 2021-07-22 13:56:54+00:00 ERROR Entrypoint: Database is uninitialized and password option is not specified mysql_1 | You need to specify one of the following:
mysql_1 | - MYSQL_ROOT_PASSWORD
mysql_1 | - MYSQL_ALLOW_EMPTY_PASSWORD
mysql_1 | - MYSQL_RANDOM_ROOT_PASSWORD
初回起動時のみ MYSQL_ALLOW_EMPTY_PASSWORD を設定
code: yaml
mysql:
environment:
MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'