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でRails8環境を作る

Posted at

Rails 8 の Docker を development で使うための環境構築方法のメモ。
データベースは SQLite3 を使う。

環境

  • WSL2
  • Ruby 3.4.6
  • Rails 8
  • Docker 28.1.1
  • Docker Compose 2.36.0-desktop.1

ファイルの準備

用意するファイルは4つ

  • Dockerfile.dev
  • compose.yaml
  • Gemfile
  • Gemfile.lock

Dockerfile.dev

最初からファイル名を Dockerfile にすると、rails new したときに上書きされてしまうので注意。
環境構築後、Dockerfile にリネームすればよい。

Dockerfile.dev
# syntax = docker/dockerfile:1

ARG RUBY_VERSION=3.4.6-slim-bookworm
FROM docker.io/library/ruby:$RUBY_VERSION

WORKDIR /app

RUN apt-get update -qq && \
    apt-get install --no-install-recommends -y \
    build-essential \
    curl \
    git \
    sqlite3 \
    libyaml-dev \
    libffi-dev \
    zlib1g-dev \
    libssl-dev \
    pkg-config && \
    curl -fsSL https://deb.nodesource.com/setup_24.x | bash - && \
    apt-get install --no-install-recommends -y nodejs && \
    rm -rf /var/lib/apt/lists /var/cache/apt/archives

ENV BUNDLE_PATH="/usr/local/bundle"

COPY Gemfile Gemfile.lock ./
RUN bundle install

ENV PATH="/usr/local/bundle/bin:$PATH"

COPY . .

EXPOSE 3000

CMD ["./bin/rails", "server", "-b", "0.0.0.0"]

compose.yaml

compose.yaml
services:
  web:
    build:
      context: .
      dockerfile: Dockerfile.dev
    ports:
      - '3000:3000'
    volumes:
      - .:/app
      # bundler cache を保持して gem の再インストールを回避
      - bundle-cache:/usr/local/bundle
    environment:
      - RAILS_ENV=development
      - RAILS_LOG_LEVEL=debug
      - BUNDLE_PATH=/usr/local/bundle
    stdin_open: true
    tty: true
    command: >
      bash -c "
        bundle check || bundle install &&
        rm -f tmp/pids/server.pid &&
        ./bin/rails server -b 0.0.0.0"

volumes:
  bundle-cache:

Gemfile

source 'https://rubygems.org'
gem 'rails', '~> 8.0'

Gemfile.lock

空のファイルを作る

Gemfile.lock

Rails アプリ作成

まず Docker のイメージをビルドする。

docker compose build

現在のディレクトリに Rails 8 アプリケーションを作成する。
rails8 という名前にしているが、ここは好みで変えてよい。

docker compose run --rm --no-deps web bundle exec rails new rails8 --force

作成された Rails アプリケーションのファイルを現在のディレクトリに移動する。

docker compose run --rm --no-deps web sh -c "cp -r rails8/* . && cp rails8/.* . 2>/dev/null || true && rm -rf rails8"

起動

docker compose up

その後

気になる場合には Dockerfile.dev を Dockerfile に上書きする。Dockerfile は rails new で作られた本番環境用のものなので、開発環境には不要。

mv Dockerfile.dev Dockerfile && sed -i 's/dockerfile: Dockerfile\.dev/dockerfile: Dockerfile/' compose.yaml
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?