せかんどくらい

転職をきっかけにとりあえずメモがわりにでもアウトプットしてみようという雑多な場所

Docker環境でのRailsプロジェクト セットアップ

概要

Docker環境でゼロからRailsプロジェクトセットアップするのが初めてだったので、作業メモ。

前提

諸々のバージョンが少し古いが公式の情報を使おうということで、このページを参考に。

docs.docker.com

  • Railsの開発環境の稼働、及びテストは全てDocker環境で行う。
  • DockerfileやGemfileは全てプロジェクトディレクトリ直下におく。
  • DBはPostgreSQLじゃなく、MySQLを使う。
  • rubyのバージョンは2.6系、Railsのバージョンは6系。

初期ファイル作成

以下のファイルを全てプロジェクトディレクトリ直下に作る。

  • Dockerfile(yarnのバージョンの不整合がおきて、webpackerがうまく動かない現象が起きるので、その辺りを修正してある。)
Dockerfile 
FROM ruby:2.6.6

RUN apt-get update -qq \
&& apt-get install -y curl apt-transport-https wget \
&& curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - \
&& echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list \
&& apt-get update && apt-get install -y yarn \
&& apt-get install -y nodejs default-mysql-client

WORKDIR /app
COPY Gemfile /app/Gemfile
COPY Gemfile.lock /app/Gemfile.lock
RUN bundle install
COPY . /app

# 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

# Start the main process.
CMD ["rails", "server", "-b", "0.0.0.0"]
  • Gemfile
source 'https://rubygems.org'
gem 'rails','~>6'
  • 空のGemfile.lock。touchするだけ。

  • entrypoint.sh

#!/bin/bash
set -e

# Remove a potentially pre-existing server.pid for Rails.
rm -f /app/tmp/pids/server.pid

# Then exec the container's main process (what's set as CMD in the Dockerfile).
exec "$@"
  • docker-compose.yml
version: '3.7'
services:
  db:
    image: mysql:8.0.20
    environment:
        MYSQL_ROOT_PASSWORD: password
    ports:
        - '3306:3306'
    command: --default-authentication-plugin=mysql_native_password
    volumes:
      - ./tmp/db:/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

Docker ビルド実行 & Rails プロジェクト作成

以下のコマンドを叩く。なお、今回はcoffee script, turbolinksは無効にするので、そのオプションもつける。

% docker-compose run web rails new . --force --no-deps --database=mysql  --skip-coffee --skip-turbolinks

Docker再ビルド

このタイミングでGemfileが書き換わるので、再ビルド

% docker-compose build

DBの接続、作成

  • config/database.ymlの修正

変更前

default: &default
  adapter: mysql2
  encoding: utf8mb4
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password: 
  host: localhost

変更後

default: &default
  adapter: mysql2
  encoding: utf8mb4
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password: password
  host: db
  • DBの作成
% docker-compose run web rails db:create

起動

% docker-compose up

確認

http://localhost:3000/ にアクセスすれば、「Yay! You're on Rails!」画面が確認できる。