LoginSignup
40
35

More than 1 year has passed since last update.

【初学者向け】DockerでRails7の環境構築(2023年版)

Posted at

Dockerの公式ドキュメントでRails7系の環境構築をしたら途中で詰まったので、スムーズに構築していく方法を記します✏️


前提条件

開発環境


この記事でわかること

Dockerの公式ドキュメントに沿ったRails7系の環境構築方法✅
(公式ドキュメント通りに行うとエラーが発生するので、本記事ではその解決方法も記します!)
※ 本記事では、DockerでRails7を最速で環境構築する方法を記します。DockerやRailsの詳しい説明については別記事をご参照ください🙏


環境構築手順

1. 任意のディレクトリを作成

Macの任意の開発スペースにアプリを作成するディレクトリを作成します✅

terminal
# mkdir お好きなアプリ名

2. Dockerfileの作成

作成したディレクトリに移動し、vscodeなどのエディタで開きます。

terminal
# cd 作成したアプリ名

Dockerfileを作成し以下を記述します✅
Rubyは任意のバージョンにしてください。

Dockerfile
FROM ruby:3.2.0
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN mkdir /myapp
WORKDIR /myapp
ADD Gemfile /myapp/Gemfile
ADD Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
ADD . /myapp

3. GemfileとGemfile.lockの作成

Gemfileを作成し以下を記述します✅
Railsバージョンを指定したい場合このタイミングで記述しておきます。
(バージョン指定がない場合は、最新の安定版になります)

Gemfile
source 'https://rubygems.org'
gem 'rails'

Gemfile.lockは空ファイルで作成します✅

Gemfile.lock

4. docker-compose.ymlの作成

Gemfileを作成し以下を記述します✅
※ こちらの記述が公式ドキュメントと異なります!
Dockerの公式ドキュメントのdocker-compose.ymlをコピペして起動するとエラーになるので注意してください⚠️

docker-compose.yml
version: '3'
services:
  db:
    image: postgres
    environment:
      - POSTGRES_PASSWORD=password
      - POSTGRES_HOST_AUTH_METHOD=trust
  web:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - db

5. rails new

Railsアプリの雛形を作ります✅
Docker Desktopを起動して、MacのメニューバーにDockerのマークが表示されていることを確認 🐳
↓コマンドを実行すれば、見慣れたRailsのファイル群が生成されます!

terminal
docker-compose run web rails new . --force --database=postgresql

6. build実行

Gemfileが書き変わったので↓コマンドを実行します✅

terminal
docker-compose build

7. database.yml書き換え

↓のように書き換えます✅
Dockerの公式ドキュメントのdatabase.ymlをコピペして起動するとエラーになるので注意してください⚠️

database.yml
default: &default
  adapter: postgresql
  encoding: unicode
  host: db
  username: postgres
  password: password
  pool: 5

development:
  <<: *default
  database: myapp_development


test:
  <<: *default
  database: myapp_test

8. DBの作成

↓コマンドを実行してDBを作成します✅

terminal
docker-compose run web rake db:create

9. 起動!!!

最後に↓コマンドで起動させると、見覚えのある画面が出てきます✅

terminal
docker-compose up

Image from Gyazo

参考にさせていただいた記事


最後に

Docker × Railsの環境構築がスムーズにいくことを願ってます🐳🚂

40
35
2

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
40
35