プログラミングのゴミ箱

日々の学習の中で知らなかったことについて、調べたことを解説します。

DockerでRails + PostgreSQLの環境を作ってみる。

Quickstart: Compose and Rails | Docker Documentation

今回はこちらのチュートリアルをやっていきます。備忘録として書いていますので読みにくいところには目を瞑ってください。

1. Dockerfileの作成

お好きな名前のフォルダを作成し、その中にDockerfileという名前のファイルを作成。そこに以下のコードを追加する。

# syntax=docker/dockerfile:1
FROM ruby:2.5 # Rubyのバージョン2.5を使用
RUN apt-get update -qq && apt-get install -y nodejs postgresql-client # ライブラリの更新とnodejs, postgresqlをインストール
WORKDIR /myapp // コマンド実行時の作業ディレクトリ指定(myappの部分はそれぞれのフォルダ名に書き換えてください)
COPY Gemfile /myapp/Gemfile # ローカルフォルダにあるGemfileをイメージにコピー
COPY Gemfile.lock /myapp/Gemfile.lock # 上と同様
RUN bundle install # package.jsonに定義されたライブラリ群をインストール

# Add a script to be executed every time the container starts.
COPY entrypoint.sh /usr/bin/ # エントリーポイントをコピー
RUN chmod +x /usr/bin/entrypoint.sh #エントリーポイントの権限を変更
ENTRYPOINT ["entrypoint.sh"] # エントリーポイントを設定
EXPOSE 3000 # 3000番ポートを公開

# Configure the main process to run when running the image
CMD ["rails", "server", "-b", "0.0.0.0"] # rails server -b 0.0.0.0を実行


2. Gemfileの作成

Gemfileという名前のファイルを作成し、以下のコードを記述する。

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

https://rubygems.orgというRubyのライブラリを共有するサイトからrailsのversion5以上を取ってくるという意味。
次に、Gemfile.lockという空のファイルを作成。


3. entrypoint.shを作成

entrypoint.shというファイルを作成し、以下のコードを記述する。

#!/bin/bash
set -e

# Remove a potentially pre-existing server.pid for Rails.
rm -f /myapp/tmp/pids/server.pid

# Then exec the container's main process (what's set as CMD in the Dockerfile).
exec "$@"

このファイルはdocker環境の初回起動時にのみ実行されるコマンドが指定される。


4. docker-compose.ymlを作成

docker-compose.ymlファイルを作成し、以下のコードを記述。

version: "3.9" #docker-composeのversion
services:
  db:
    image: postgres # postgresImageを使用
    volumes:
      - ./tmp/db:/var/lib/postgresql/data # イメージの中の/var/lib/postgresql/dataを./tmp/dbにマウント
    environment:
      POSTGRES_PASSWORD: password # 環境変数を指定
  web:
    build: . # Dockerfileの場所を指定
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'" # 起動時の実行コマンドを指定
    volumes:
      - .:/myapp # イメージの/myappを現在のディレクトリにマウント
    ports:
      - "3000:3000" # 公開するポートを指定
    depends_on:
      - db # dbが起動した後に起動する


5. Railsアプリの作成

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

このコマンドを実行して新しいrailsアプリを作成。

 docker-compose build

ついでにこのコマンドでビルド。


6. railsをデータベースに接続

config/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


7. Railsの立ち上げとデータベースの作成

以下のコードを実行。

docker-compose up
docker-compose run web rake db:create

f:id:chanichiwasshoi:20220221003818p:plain

無事立ち上がった。