Closed7

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

おとのおとの

開発環境設定に必要なファイルを作成

  1. 以下コマンドを実行し、各ファイルを作成します。
touch Gemfile Gemfile.lock Dockerfile docker-compose.yml
  1. Gemfileに以下記述を追加します。
Gemfile
source "https://rubygems.org"
gem 'rails'
  1. 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}
  1. 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

参考

https://qiita.com/Yusuke_Hoirta/items/3a50d066af3bafbb8641

おとのおとの

Railsアプリケーションの作成

  1. 以下コマンドを実行し、アプリケーションのビルドを行います。
docker compose build
docker compose run --rm --no-deps web rails new . --api --force -d=postgresql

※APIモードで作成しない場合は--apiを削除してコマンド実行してください。

おとのおとの

DBを作成する(PostgreSQL)

  1. 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 } %>
  1. 以下コマンドを実行し、もう一度ビルドします。
docker compose build
  1. 以下コマンドを実行し、DBを作成します。
docker compose run --rm web rake db:create
おとのおとの

実際にRailsアプリケーションを立ち上げてみる

以下コマンドを実行し、Railsの画面がhttp://localhost:3000/で立ち上がることを確認してください。

docker compose up -d

このスクラップは2024/11/29にクローズされました