Railsチュートリアルで作成したサンプルアプリをDockerで動かす手順
雑に備忘録
基本的な内容は下記ページに書かれているもので、それをRailsチュートリアルで作成したサンプルアプリ向けにまとめました。
docs.docker.com
ローカルPCで動かす想定です。
以下、コマンドとファイルの記載内容
nano 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 Gemfile /sample-app/Gemfile COPY Gemfile.lock /sample-app/Gemfile.lock RUN bundle install 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サイトのテンプレートから「Myapp」を「sample-app」に置き換えています。
nano Gemfile
source 'https://rubygems.org' gem 'rails', '~>5'
touch Gemfile.lock
nano 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 "$@"
nano docker-compose.yml
version: '3' services: db: image: postgres volumes: - ./tmp/db:/var/lib/postgresql/data environment: POSTGRES_PASSWORD: password web: 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サイトのテンプレートから「Myapp」を「sample-app」に置き換えています。
リポジトリのクローン
git clone [リポジトリのURL]
リポジトリのファイルを移動
cd sample_app mv * ../ mv .git ../ mv .gitignore ../ cd .. rm -rf sample_app
イメージ作成
docker-compose build
データベース作成
docker-compose run web rake db:create
データベースのマイグレーション
docker-compose run web rake db:migrate
サンプルデータの反映
docker-compose run web rake db:seed
アプリケーションのコンテナ起動
docker-compose up
完了
余談
Postgresqlのコンテナ起動してもRails側でDBの設定変えないとデフォルトのSQLite使っちゃいます。
Dockerfile、docker-compose.yml、entrypoint.sh、Gemfile.lockはリポジトリに入れておくと便利です。