Closed7
Docker + Ruby on Rails 7の開発環境を構築する(M1 Mac)

開発環境設定に必要なファイルを作成
- 以下コマンドを実行し、各ファイルを作成します。
touch Gemfile Gemfile.lock Dockerfile docker-compose.yml
-
Gemfile
に以下記述を追加します。
Gemfile
source "https://rubygems.org"
gem 'rails'
-
Dockerfile
に以下記述を追加します。
Dockerfile
FROM ruby:3.1.2
RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -\
&& echo 'deb http://dl.yarnpkg.com/debian/ stable main' > /etc/apt/sources.list.d/yarn.list
RUN curl -sL https://deb.nodesource.com/setup_16.x | bash -
RUN apt update -qq && apt install -y nodejs build-essential postgresql-client yarn \
curl dirmngr apt-transport-https lsb-release ca-certificates
ENV APP_ROOT /app
RUN mkdir ${APP_ROOT}
WORKDIR ${APP_ROOT}
ADD ./Gemfile ${APP_ROOT}/Gemfile
ADD ./Gemfile.lock ${APP_ROOT}/Gemfile.lock
RUN bundle install
ADD . ${APP_ROOT}
-
docker-compose.yml
に以下記述を追加します。
docker-compose.yml
version: '3'
services:
db:
image: postgres:14.2
volumes:
- ./tmp/db:/var/lib/postgresql/data
environment:
- POSTGRES_PASSWORD=postgres
- POSTGRES_USER=postgres
web:
build: .
environment:
RAILS_ENV: development
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
参考

Railsアプリケーションの作成
- 以下コマンドを実行し、アプリケーションのビルドを行います。
docker compose build
docker compose run --rm --no-deps web rails new . --api --force -d=postgresql
※APIモードで作成しない場合は--api
を削除してコマンド実行してください。

DBを作成する(PostgreSQL)
-
database.yml
を修正します。
database.yml
default: &default
adapter: postgresql
encoding: unicode
+ host: db
+ username: postgres # docker-compose.ymlの記載内容と同じ値に設定
+ password: postgres # docker-compose.ymlの記載内容と同じ値に設定
# For details on connection pooling, see Rails configuration guide
# https://guides.rubyonrails.org/configuring.html#database-pooling
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
- 以下コマンドを実行し、もう一度ビルドします。
docker compose build
- 以下コマンドを実行し、DBを作成します。
docker compose run --rm web rake db:create

実際にRailsアプリケーションを立ち上げてみる
以下コマンドを実行し、Railsの画面がhttp://localhost:3000/で立ち上がることを確認してください。
docker compose up -d

下記記事を参考にAPIを作ってみた。楽しい。

format設定を以下を参考に実装してみる。
このスクラップは2024/11/29にクローズされました