はじめに
既存のRailsアプリをDocker化していきます!
最終的にはdocker-compose upを行い、「http://localhost:3000」で
アプリケーションが立ち上がる状態を作ることがゴールです。
成果物
- 最終的には下記のようなDockerfileとdocker-compose.ymlができる想定です。また、最後はREADMEも記述していきます。
Dockerfile
FROM ruby
RUN apt-get update && apt-get install -y \
build-essential \
libpq-dev \
node.js \
postgresql-client \
yarn
WORKDIR /rails-docker
COPY Gemfile Gemfile.lock /rails-docker/
RUN bundle install
docker-compose.yml
version : "3"
volumes:
db-data:
services:
web:
build: .
command: rails s -p 3000 -b '0.0.0.0' -u puma
ports:
- '3000:3000'
volumes:
- '.:/rails-docker'
# コンテナ側の環境変数に設定する
environment:
- 'DATABASE_PASSWORD=postgres'
- 'POSTGRES_PASSWORD=postgres'
tty: true
stdin_open: true
# DBの立ち上がりを待機する
depends_on:
db:
condition: service_healthy
links:
- db
db:
image: postgres
volumes:
- 'db-data:/var/lib/postgresql/data'
environment:
- 'POSTGRES_DB=postgres'
- 'POSTGRES_USER=postgres'
- 'POSTGRES_PASSWORD=postgres'
healthcheck:
test: ["CMD", "psql", "-U", "postgres", "-c", "SELECT 1"]
interval: 6s
timeout: 10s
retries: 5
解説
Dockerfile のポイント解説
Dockerfile
FROM ruby
RUN ・・・(省略)
(1) FROMで指定するのはlatest(最新バージョン)が適切か、versionを指定した方が良いかはプロジェクトに左右されます。適切なバージョンの確認は、プロジェクトのGemfileを参照することで可能です。
Gemfile
ruby "3.2.2"
# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main"
gem "rails", "~> 7.0.6"
(2) RUNでは、なるべく少ない行で書くことを意識することが重要です。なぜなら、RUNが増えると、その分レイヤーが増えてしまうからです。また、ここで必要なコマンドはアプリケーションによるので、環境ごとに異なると思います。
Dockerfile
RUN apt-get update && apt-get install -y \
build-essential \
libpq-dev \
node.js \
postgresql-client \
yarn
WORKDIR・・・(省略)
docker-compose.yml のポイント解説
docker-compose.yml
command: rails s -p 3000 -b '0.0.0.0' -u puma
(1) 特筆するべき点としては、-uでWebアプリアプリケーションサーバを指定しています。理由としては、ローカル環境では指定しなくても大丈夫でしたが、GitHub Actionの自動テストで指摘されましたので、指定しています。指摘内容は下記です。
`handle_argument_error': ERROR: "rails server" was called with arguments ["bin/setup"] (Thor::InvocationError)
Usage: "rails server -u [thin/puma/webrick] [options]"
(2) depends_onは起動順を制御しますが、依存先が起動したかどうかまでは検知してくれていません。
なので、念のためcondition: service_healthyを使用してDBの起動を確認した後に、Webアプリアプリケーションサーバの起動するように制御をしています。
- web側
docker-compose.yml
# DBの立ち上がりを待機する
depends_on:
db:
condition: service_healthy
links:
- db
- db側(疎通確認ができれば良いので任意のコマンドで構いません)
docker-compose.yml
healthcheck:
test: ["CMD", "psql", "-U", "postgres", "-c", "SELECT 1"]
interval: 6s
timeout: 10s
retries: 5
参考記事↓
READMEを書く✍️
README.md
* git clone <this repository>
* cd rails-docker
* docker-compose up --build -d
* docker-compose exec db bash
* rails db:create ※First time only
* rails db:migrate ※First time only
* access this URL → http://localhost:3000
- 最後にREADMEを書いていきましょう。
- READMEは(シチュエーションにもよりますが)なるべく全く仕様や使い方がわからない人向けに記述すると後に同じアプリを構築する人にとって親切なものになると思います。