11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Ruby 3.1 + Rails 7 + MySQL 8 + Docker 環境構築

Posted at

Ruby 3.1 + Rails 7 + MySQL 8 + Docker で環境構築する方法を紹介します

1. 5つのファイルを作成する

用意するファイル

  • Dockerfile
  • docker-compose.yml
  • entrypoint.sh
  • Gemfile
  • Gemfile.lock
Dockerfile
FROM ruby:3.1
ARG RUBYGEMS_VERSION=3.3.20
RUN mkdir /rails_practice
WORKDIR /rails_practice
COPY Gemfile /rails_practice/Gemfile
COPY Gemfile.lock /rails_practice/Gemfile.lock
RUN bundle install
COPY . /rails_practice

COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

CMD ["rails", "server", "-b", "0.0.0.0"]
docker-compose.yml
version: '3'
services:
  db:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: password
    ports:
      - '3306:3306'
    command: --default-authentication-plugin=mysql_native_password
    volumes:
      - mysql-data:/var/lib/mysql
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/rails_practice
    ports:
      - "3000:3000"
    depends_on:
      - db
    stdin_open: true
    tty: true
volumes:
  mysql-data:
    driver: local

以前のバージョンの MySQL ではデフォルトで使用していた認証プラグインがmysql_native_password でしたが、 MySQL 8.0 以降は caching_sha2_password に変更となりました。
今回はmysql_native_passwordを使用しています。
(Railsはcaching_sha2_password未対応?)

entrypoint.sh
#!/bin/bash
set -e

rm -f /docker_rails/tmp/pids/server.pid

exec "$@"
Gemfile
source 'https://rubygems.org'
gem 'rails', '~>7.0.4'

Gemfile.lockという空ファイルを作ります

touch Gemfile.lock

2. Rails アプリケーション新規作成

docker-compose run web rails new . --force --no-deps --database=mysql --skip-test --webpacker
docker-compose build

3. データベース接続

database.yml
default: &default
  adapter: mysql2
  encoding: utf8mb4
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: <%= ENV.fetch("MYSQL_USERNAME", "root") %>
  password: <%= ENV.fetch("MYSQL_PASSWORD", "password") %>
  host: <%= ENV.fetch("MYSQL_HOST", "db") %>

development:
  <<: *default
  database: rails_practice_development
docker-compose run web rake db:create

4. 実行

docker-compose up

実行できたら成功です。
スクリーンショット 2023-04-10 7.09.16.png

PS. 失敗してリセットする魔法

作成したdockerコンテナをすべて削除する

docker-compose down --rmi all --volumes --remove-orphans
11
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?