1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

rails7 + postgreSQL + docker 環境構築

Last updated at Posted at 2025-03-30

目的

自己学習の備忘録

環境

・macOS:15.1.1
・ruby:3.2.2
・rails:7.1.3
・docker:27.1.2

前提

・railsプロジェクト立ち上げ済み
・dockerインストール済み

環境構築手順

railsアプリにgem pg をインストール

railsがpostgresqlを操作するために必要

gem 'pg', '~> 1.5.9'
bundle install

docker composeの設定

services:
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -b '0.0.0.0'"
    ports:
      - "3000:3000"
    volumes:
      - .:/rails_test_app
    depends_on:
      - db

  db:
    image: postgres:17
    environment:
      POSTGRES_USER: 任意のユーザー名
      POSTGRES_PASSWORD: 任意のパスワード
    ports:
      - "5432:5432"
    volumes:
      - rails_test_app_data:/var/lib/postgresql/data

volumes:
  rails_test_app_data:

・rm -f tmp/pids/server.pid && bundle exec rails s -b '0.0.0.0'
railsサーバが起動する時に作成されるtmp/pids/server.pidファイルを削除してからサーバを起動するようにする
(railsサーバが異常終了した時など、新たにサーバを起動する際に古いpidファイルが残っているケースがあるため、毎回pidファイルを削除してからサーバを起動するようにする)

・volumes: .:/rails_test_app
ローカルディレクトリの/rails_test_appをマウント先とすることで、ローカルでファイル更新があってもリアルタイムでコンテナにも反映できる

・volumes: rails_test_app_data:/var/lib/postgresql/data
dbコンテナ内のDBファイルが置かれているディレクトリをコンテナ外で用意されているdockerボリューム(rails_test_app_data)に保存する

・volumes: rails_test_app_data:
ボリュームを使うために宣言する

railsのDB設定

host: はコンテナ名のdbをデフォルト値とする
(Dockerネットワークという概念で、コンテナ間の接続はコンテナ名を指定することで接続可能となる)

default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS", 5) %>
  username: <%= ENV.fetch("POSTGRES_USER", '任意のユーザー名') %>
  password: <%= ENV.fetch("POSTGRES_PASSWORD", '任意のパスワード') %>
  host: <%= ENV.fetch("POSTGRES_HOST", 'db') %>

development:
  <<: *default
  database: development_db

test:
  <<: *default
  database: test_db

production:
  <<: *default
  database: production_db

Dockerfileの設定

初期railsアプリを起動させる最小限の設定

FROM ruby:3.2.2

RUN apt-get update -qq && apt-get install -y \
  postgresql-client

WORKDIR /rails_test_app

COPY Gemfile /rails_test_app/Gemfile
COPY Gemfile.lock /rails_test_app/Gemfile.lock

RUN bundle install

COPY . /rails_test_app

・postgresql-client
dbコンテナで動くpostgresqlに直接入って作業したい場合に必要(コマンドは↓)

docker compose exec web psql -U ユーザー名 -h db 

・WORKDIR /rails_test_app
以降のCOPYやRUNを実行する作業ディレクトリを指定する

・COPY Gemfile /rails_test_app/Gemfile
COPY <ローカルディレクトリのコピー元> <webコンテナ内のコピー先>

動作確認

docker compose up
docker compose exec web bin/rails db:create 

http://localhost:3000にアクセスして以下の画面になればOK

スクリーンショット 2025-03-30 13.37.32.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?