1
3

More than 1 year has passed since last update.

はじめてのDockerでRails7の環境構築

Last updated at Posted at 2023-07-19

Dockerクイックスタートに倣いRails7の環境構築を行いました。
環境は以下の通りです。

  • Ruby: 3.2.2
  • Ruby on Rails: 7.0.6
  • Postgres: 12

前提

本記事でわかること

  • DockerによるRails7環境構築

作業ディレクトリの作成

作業用に任意ディレクトリ(本記事ではrails-docker)を作成します。

terminal
# mkdir rails-docker

Dockerfileの作成

前項で作成したディレクトリに移動します。

terminal
# cd rails-docker

次にDockerfileを新規作成して以下を記述します。


Dockerfile
FROM ruby:3.2.2
RUN apt-get update && apt-get install -y \
    build-essential \
    libpq-dev \
    nodejs

WORKDIR /rails-docker
COPY Gemfile /rails-docker/
COPY Gemfile.lock /rails-docker/
RUN bundle install
COPY . /rails-docker

GemfileとGemfile.lockの作成

GemfileGemfile.lockを新規作成する。
Gemfileは以下を記述し、Gemfile.lockは空ファイルとします。

Gemfile
source 'https://rubygems.org'
gem "rails", "~> 7.0.6"
Gemfile.lock

docker-compose.ymlの作成

docker-compose.ymlを新規作成し、以下を記述する。
volume- .:/rails-dockerによりホスト側のdocker-compose.ymlがあるディレクトリをコンテナ内のdocker-railsの関連付けています。

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

rails new を実行する

docker-compose runを実行することで、Railsアプリのひながたを生成する。

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

imageをbuildする

Linux上でDockerを動作している場合はrails newによる生成ファイルの所有者がrootになっているのでsudo chown -R $USER:$USER .を実行してからイメージをビルドしてください。

前項のrails newGemfileが更新されました。
更新されたGemfilebundle installしたイメージを再度ビルドするためにdocker-compose buildを実行します。

terminal
# docker-compose build

database.ymlの修正

Railsアプリのデータベース接続設定をdbサービスに接続するために
config/database.ymldefault: &defaultに以下の記述を追加します。

database.yml
  host: db
  username: postgres
  password:

データベースの生成

docker-compose.ymlがあるディレクトリで以下のコマンドを実行することでデータベースを生成する。

terminal
# docker-compose run web rails db:create

docker-composeでコンテナを起動する

terminal
# docker-compose up

ブラウザを起動してhttp://localhost:3000/にアクセスすればRails起動画面が表示されます。
image.png

参考

1
3
0

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
1
3