個人開発をしていた際、rails dbconsole
を実行したところCouldn't find database client: mysql, mysql5. Check your $PATH and try again.
というエラーが出ました。
原因がわかったので解決方法を備忘録としてまとめます。
- Ruby 3.2.2
- Rails 7.1.2
- MySQL 8.0
問題
Railsのマイグレーションで不整合が発生したため、調査のためにMySQLの中身を見ようとしていました。
しかし、rails dbconsole
を実行したところ、Couldn't find database client: mysql, mysql5. Check your $PATH and try again.
とエラーが出てしまい、MySQLの中に入れない状況でした。
$ docker compose -f compose-dev.yaml exec web bash
$ root@2cccb198027f:/sample-api# rails dbconsole
Couldn't find database client: mysql, mysql5. Check your $PATH and try again.
使っていたDockerfileとcompose.yamlは次の通りです。
※開発環境と本番環境でファイルを分けているため、それぞれDockerfile.devとcompose-dev.yamlと名付けています。
Dockerfile.dev
# syntax=docker/dockerfile:1
FROM ruby:3.2.2
WORKDIR /sample-api
COPY Gemfile /sample-api/Gemfile
COPY Gemfile.lock /sample-api/Gemfile.lock
RUN bundle install
# Add a script to be executed every time the container starts.
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000
# Configure the main process to run when running the image
CMD ["rails", "server", "-b", "0.0.0.0"]
compose-dev.yaml
services:
db:
image: mysql:8.0
volumes:
- db-data:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: password
ports:
- "3306:3306"
web:
build:
context: .
dockerfile: Dockerfile.dev
volumes:
- .:/sample-api
ports:
- "3000:3000"
depends_on:
- db
volumes:
db-data:
解決方法
Dockerfileの中でmysql-client
をインストールしていないことが原因でした。
以下のようにDockerfile.devを修正します。
# syntax=docker/dockerfile:1
FROM ruby:3.2.2
# 下記の1行を追加
RUN apt-get update -qq && apt-get install -y default-mysql-client
WORKDIR /sample-api
COPY Gemfile /sample-api/Gemfile
COPY Gemfile.lock /sample-api/Gemfile.lock
RUN bundle install
# Add a script to be executed every time the container starts.
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000
# Configure the main process to run when running the image
CMD ["rails", "server", "-b", "0.0.0.0"]
mysql-client
ではなくdefault-mysql-client
としないとエラーが起きてしまうので要注意です。
修正が完了したらもう一度ビルドし、コンテナを立ち上げましょう。
$ docker compose -f compose-dev.yaml build
$ docker compose -f compose-dev.yaml up
コンテナの中に入り再度rails dbconsole
を実行してみると、、、
$ docker compose -f compose-dev.yaml exec web bash
$ root@2cccb198027f:/sample-api# rails dbconsole
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 14
Server version: 8.0.35 MySQL Community Server - GPL
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MySQL [sample_api_development]>
MySQLコンテナの中に入ることができました!!
おわりに
Dockerは日々の業務でも使っていますが、Dockerfileを自力で書くにはもっとしっかりDocker周りの勉強をした方が良さそうだと感じました。
コメント