公式ドキュメントがあったのでそれを参考にバージョンとかを変えてある。細かい説明は抜きに単純な手順として纏めてみた。
@Contents
開発環境やバージョン
- macOS Catalina 10.15.7
- IntelliJ IDEA Ultimate 2020.3 -> Rubyプラグイン
- Docker 20.10.0
- Ruby 2.7.2
- Rails 6.1.0
- Docker Compose 1.27.4
- MySQL 8.0
色々と便利なのでIDEを使っているがCLIでも不自由なくDockerで開発環境を構築可能。本当はRubyMine使いたいけどなぁ……。
構築の手順
まずはIntelliJでFile -> New -> ProjectでRuby on Railsを選択し、名前を付けて作成。
次にDockerの設定をしていく。順不同で以下の5つのファイルをプロジェクト直下に作成する。ちなみにこのサンプルではeasy-messages
というプロジェクト名にしてるからそこは書き換える必要がある。
Dockerfile
FROM ruby:2.7
RUN 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 -qq \
&& apt-get install -y nodejs yarn \
&& mkdir /easy-messages
WORKDIR /easy-messages
COPY Gemfile /easy-messages/Gemfile
COPY Gemfile.lock /easy-messages/Gemfile.lock
RUN bundle install
COPY . /easy-messages
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:
- .:/easy-messages
ports:
- "3000:3000"
depends_on:
- db
stdin_open: true
tty: true
volumes:
mysql-data:
driver: local
Gemfile
source 'https://rubygems.org'
gem 'rails', '~>6'
Gemfile.lock
entrypoint.sh
#!/bin/bash
set -e
# Remove a potentially pre-existing server.pid for Rails.
rm -f /myapp/tmp/pids/server.pid
# Then exec the container's main process (what's set as CMD in the Dockerfile).
exec "$@"
コマンドの実行
Railsプロジェクトを生成
% docker-compose run web rails new . --force --no-deps --database=mysql --skip-test --webpacker
Dockerイメージのビルド
% docker-compose build
データベースの設定ファイルを編集
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: easy-messages_development
test:
<<: *default
database: easy-messages_test
production:
<<: *default
database: easy-messages_production
username: easy-messages
password: <%= ENV['EASY-MESSAGES_DATABASE_PASSWORD'] %>
データベースを作成
% docker-compose run web rake db:create
コンテナを起動
% docker-compose up
Listening onの後にURIが表示されているのでそこにアクセスすればOK。
