LoginSignup
3
3

More than 1 year has passed since last update.

Docker で Rails 7 + MySQL 8.0(mysql-server) の環境を構築する(Compose V2)(M1 Mac)

Last updated at Posted at 2022-10-01

作業内容

ディレクトリ構成

myrailsapp/
├── Dockerfile
├── compose.yaml
├── entrypoint.sh
├── Gemfile
└── Gemfile.lock

ファイルの準備

Dockerfile
FROM ruby:3.1.2

RUN mkdir /app
WORKDIR /app
COPY Gemfile /app/Gemfile
COPY Gemfile.lock /app/Gemfile.lock

RUN gem update --system
RUN bundle update --bundler

RUN bundle install
COPY . /app

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"]
compose.yaml
services:
  db:
    image: mysql/mysql-server:latest
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_ROOT_HOST: '%'
    ports:
      - "3306:3306"
    volumes:
      - db-volume:/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:
      - .:/app
    ports:
      - "3000:3000"
    depends_on:
      - db
volumes:
  db-volume:
entrypoint.sh
#!/bin/bash
set -e

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

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

Gemfile.lockは空でよい。

Railsプロジェクト作成

注意Compose V2が有効になっていることを確認する。

docker compose run --rm web rails new . --force --no-deps --database=mysql

Dockerfileからイメージ作成

docker compose build

DB接続設定

config > database.yml > defaultの記述を変更。

config/defaultdatabase.yml
# この箇所以外はそのままでよい。
default: &default
  adapter: mysql2
  encoding: utf8mb4
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password: root
  host: db

DB作成

docker compose run --rm web rails db:create

コンテナ起動

docker compose up

http://localhost:3000 にアクセス。Railsアプリが起動していることを確認する。

補足

Bundler

以下のイシューにある通り、Bundlerのバグにより正常にGemをインストールしてくれなかった。

イシューのスレッドにある通り、Bundlerをアップデートしてやることで解決。

Dockerfile
...
RUN gem update --system
RUN bundle update --bundler
...

MySQL

こちらを参照。

参考にしたサイト

3
3
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
3
3