DockerでRailsチュートリアル

DockerでRailsチュートリアルの開発ができるようにします。

近年は、docker-composeが主流となっていると思うのでdocker-composeを使う。

環境
Railsチュートリアルの全章が終了した状態
Mac
Dockerはインストール済み

Docker-composeのインストール

Docker Desktop for Mac and Docker Toolbox already include Compose along with other Docker apps, so Mac users do not need to install Compose separately.

引用文から、Docker for Macを準備できた時点でDocker-composeも使えるようです。

試しに、端末でdocker-compose コマンドを実行するとリファレンスが表示されますね。

Install Docker Compose | Docker Documentation

set -e

「set」はシェルの設定を確認、変更するコマンド

「set -e」でコマンド実行時にエラーになれば即座にシェルを終了する

linux - What does set -e mean in a bash script? - Stack Overflow

rails server --help

-p, [--port=port] # Runs Rails on the specified port - defaults to 3000.
-b, [--binding=IP] # Binds Rails to the specified IP - defaults to 'localhost' in development and '0.0.0.0' in other environments'.

「-p」は、ポートを指定

「-b」は、特定IPアドレスへの外部公開設定。「0.0.0.0」はローカルマシン上の全てのIPv4アドレスである。

つまり、「-b 0.0.0.0」でローカルマシン上の全てのIPv4アドレスに外部公開可能となる。

本題

[Dockerfile]
FROM ruby:2.5
RUN apt-get update -qq && apt-get install -y nodejs postgresql-client
RUN mkdir /sample_app
WORKDIR /sample_app
COPY . /sample_app

# 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

# Start the main process.
CMD ["rails", "server", "-b", "0.0.0.0"]

  

[docker-compose.yml]
version: '3'
services:
  db:
    image: postgres
    volumes:
      - ./tmp/db:/var/lib/postgresql/data
  app:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/sample_app
    ports:
      - "3000:3000"
    depends_on:
      - db

とした後、docker-compose run app するとbundleがinstallされていないという

エラーが出た

bundler: command not found: rails Install missing gem executables with bundle install

解決策としては

以下のようにDockerfileを編集して

docker-compose builddocker-compose up を行うと

Railsチュートリアルが立ち上がる。

[Dockerfile]
FROM ruby:2.5
RUN apt-get update -qq && apt-get install -y nodejs postgresql-client
ENV APP_ROOT /sample_app
RUN mkdir $APP_ROOT

WORKDIR $APP_ROOT
ADD Gemfile $APP_ROOT
ADD Gemfile.lock $APP_ROOT
RUN  bundle install

ADD . $APP_ROOT

CMD ["set", "-e"]
EXPOSE 3000

# Start the main process.
CMD ["rails", "server", "-b", "0.0.0.0"]

Quickstart: Compose and Rails | Docker Documentation