LoginSignup
kajiyai
@kajiyai

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

ActiveRecord::DatabaseConnectionErrorの解消

ActiveRecord::DatabaseConnectionErrorの解消

やりたいこと

  • DockerでRailsとMySQLを接続し、ハローワールドしたい

エラー内容

**ActiveRecord::DatabaseConnectionError
There is an issue connecting to your database with your username/password, username: root.
Please check your database configuration to ensure the username/password are valid.**
Mysql2::Error::ConnectionError: Access denied for user 'root'@'172.23.0.3' (using password: YES)

docker compose up でコンテナを立ち上げ、localhost.3000を訪れると上記エラーが返される
別ターミナルでdocker compose run web rake db:createを打っても同様

調査

  • 公式をちゃんと読む

postgresの説明だが、デフォルトだとlocalhostに行っちゃうからdbにしとけよ、と書かれてる

The app is now bootable, but you're not quite there yet. By default, Rails expects a database to be running on localhost - so you need to point it at the db container instead. You also need to change the database and username to align with the defaults set by the postgres image.

自分の理解のメモ

config/database.ymlはrails側の設定で、docker-compose.ymlはdockerのコンテナの設定。

  • config/database.ymlについて

    • adapter, encoding,ユーザー名、パス、ホスト等を指定する。
  • docker-compose.ymlについて

    • 今回はサービスが二つ、dbとwebがあり、二つコンテナがある。サービスdbの中のenvironmentに環境変数を記述でき、userやpassを記述した

原因

  • おそらく、docker-compose.ymlとconfig/database.ymlの間における情報の齟齬

  • docker-compose.yml側

services:
  db:
    image: mysql:latest
    ports:
      - "13306:3306"
    volumes:
      - ./.data/db:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_USER: user
      MYSQL_PASSWORD: password
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - db
  • config/database.yml側
default: &default
  adapter: mysql2
  encoding: utf8mb4
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: user
  password: password
  host: db

development:
  <<: *default
  database: myapp_development

試したこと

  • config/database.ymlファイルの改行コードをLFにする
  • Docker上でMySQLの対話モードに入ろうとする
    • 変わらず
  • docker-compose.ymlのMYSQL_USER, MYSQL_PASSWORDを削除、config/database.ymlのusernameをuserに
    • 変わらず
  • docker volume lsを打って、volumeの確認
    • ない
  • コンテナ削除、イメージ削除から作り直し2回
    • 変わらず

参考

こちらのgithubを元にpostgresではなくmysqlで進めていた

1

1Answer

Comments

  1. @kajiyai

    Questioner

    ありがとうございます!!
    参考にさせて頂きました!

Your answer might help someone💌