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

🚀 DockerでRuby on Rails開発環境を構築する(PostgreSQL対応

Last updated at Posted at 2025-05-14

📁 構成ファイルの作成

Railsアプリケーションの開発環境をDockerで簡単に構築する方法を紹介します。
今回は Rails 7.2 + PostgreSQL + Docker Compose を使った環境を構築します。

まず、以下のコマンドでファイルを作成する。

touch Dockerfile docker-compose.yml Gemfile Gemfile.lock entrypoint.sh

ファイルの中身を以下のようにする。

dockerfile
FROM ruby:3.3

RUN apt-get update -qq && \
    apt-get install -y --no-install-recommends \
    build-essential \
    libpq-dev \
    libyaml-dev \
    nodejs \
    yarn \
    git && \
    rm -rf /var/lib/apt/lists/*

WORKDIR /myapp

COPY Gemfile Gemfile.lock ./
RUN gem install bundler
RUN bundle install && \
    rm -rf ~/.bundle/ /usr/local/bundle/cache /usr/local/bundle/ruby/*/bundler/gems/*/.git

COPY . .

# entrypoint.shの追加
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]

EXPOSE 3000

CMD ["rails", "server", "-b", "0.0.0.0"]
docker-compose.yml
version: '3.9'

services:
  db:
    image: postgres:15
    volumes:
      - postgres-data:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: password
      POSTGRES_USER: postgres
    ports:
      - "5432:5432"

  web:
    build: .
    command: rails server -b 0.0.0.0
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    environment:
      RAILS_ENV: development
      DATABASE_HOST: db
      DATABASE_USERNAME: postgres
      DATABASE_PASSWORD: password
    depends_on:
      - db

volumes:
  postgres-data:
entrypoint.sh
#!/bin/bash
set -e

rm -f tmp/pids/server.pid

exec "$@"
Gemfile
source 'https://rubygems.org'
gem 'rails', '~> 7.2'

これらのファイルを作成して以下のコマンドを入力する。

docker compose run --rm web rails new . --database=postgresql
docker compose run --rm web bundle install

そして、DB設計をする。

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

development:
  <<: *default
  database: myapp_development

test:
  <<: *default
  database: myapp_test

そして、以下のコマンドでビルドして実行する。

docker-compose build
docker-compose up

そして、以下のコマンドでデータベースを作成する。

docker compose exec web rails db:create
docker compose exec web rails db:migrate

そして、以下のurlでアクセスする。

localhost:3000
0
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
0
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?