💭

"docker-compose run --rm rails rails db:create"がコケた時に確認すべきこと

2022/06/19に公開

事象

$ docker-compose run --rm rails rails db:create

で以下のようにコケた.

Creating lamp_rails_run ... done
Unknown MySQL server host 'mysql' (-2)
Couldn't create 'db_dev' database. Please check your configuration.
rails aborted!
Mysql2::Error::ConnectionError: Unknown MySQL server host 'mysql' (-2)
/usr/local/bundle/gems/mysql2-0.5.4/lib/mysql2/client.rb:95:in `connect'
...(中略)...
Tasks: TOP => db:create
(See full trace by running task with --trace)
ERROR: 1

調査

$ docker-compose logs mysql

↓↓↓

mysql_1  | 2022-06-17 15:16:53+00:00 [ERROR] [Entrypoint]: MYSQL_USER="root", MYSQL_USER and MYSQL_PASSWORD are for configuring a regular user and cannot be used for the root user
mysql_1  |     Remove MYSQL_USER="root" and use one of the following to control the root user password:
mysql_1  |     - MYSQL_ROOT_PASSWORD
mysql_1  |     - MYSQL_ALLOW_EMPTY_PASSWORD
mysql_1  |     - MYSQL_RANDOM_ROOT_PASSWORD

Remove MYSQL_USER="root" and use one of the following to control the root user password: MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD, MYSQL_RANDOM_ROOT_PASSWORD とのこと.

解決策

現時点の設定:

services:
  mysql:
    build: 'mysql'
    environment:
      MYSQL_DATABASE: 'testdb'
      MYSQL_USER: 'root'
      MYSQL_PASSWORD: 'password'
      MYSQL_ROOT_PASSWORD: 'password'
...

メッセージのとおり以下のように対応した.

services:
  mysql:
    build: 'mysql'
    environment:
      MYSQL_DATABASE: 'testdb'
      #MYSQL_USER: 'root'              <=== コメントアウト
      MYSQL_PASSWORD: 'password'
      MYSQL_ROOT_PASSWORD: 'password'
...

以上の結果,db:createが正常に完了した.

$ docker-compose run --rm rails rails db:create

↓↓↓

Creating lamp_rails_run ... done
Created database 'db_dev'
Created database 'db_tes'

Discussion