Railsプロジェクト 初回セットアップ
前提
10年ぶり近くでRailsを触ることになったので、初心者のつもりでゼロからセットアップ。
当時はDockerもなかったのでDockerに慣れていくことも兼ねる。
環境
至って普通。
必要なファイルの用意
- Dockerfileを作る。注意することろはyarn。普通にapt-getで入れるだけだとyarnのバージョンに問題があり、あとでwebpackが入らない。
FROM ruby:2.6.6 RUN apt-get update -qq \ && apt-get install -y curl apt-transport-https wget \ && curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - \ && echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list \ && apt-get update && apt-get install -y yarn \ && apt-get install -y nodejs default-mysql-client WORKDIR /app COPY Gemfile /app/Gemfile COPY Gemfile.lock /app/Gemfile.lock RUN bundle install COPY . /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"]
- Gemfileを作る。このファイルはあとでrails newを実行した際に上書きされる。
source 'https://rubygems.org' gem 'rails', '~>6.0.2'
空のGemfile.lockを作る。
entrypoint.shを作る
#!/bin/bash set -e # Remove a potentially pre-existing server.pid for Rails. rm -f /app/tmp/pids/server.pid # Then exec the container's main process (what's set as CMD in the Dockerfile). exec "$@"
- docker-compose.ymlを作る
version: '3.7' services: db: image: mysql:8.0.20 environment: MYSQL_ROOT_PASSWORD: password ports: - '3306:3306' command: --default-authentication-plugin=mysql_native_password volumes: - ./tmp/db:/var/lib/mysql web: build: . command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'" volumes: - .:/app ports: - "3000:3000" depends_on: - db
ビルド実行
% docker-compose run web rails new . --force --no-deps --database=mysql
今思えばこの時にtubolinksとか無効にしておけばよかった。Gemfileはこのタイミングで更新される。
Gemfileが書き換わったので再ビルド
% docker-compose build
Webpackerのインストール
docker-compose upで立ち上げようとするが、config/webpacker.ymlがないと言われて落ちる。webpackerをインストールしないといけないと知る。
% docker-compose run web rails webpacker:install
ここでyarnが入っていなかったり、前述の通りyarnのバージョンがあってないせいでエラー(ArgumentError: Malformed version number string 0.32+git)が発生。 Dockerfileを修正して(上のファイルは修正済み)再ビルド。再ビルド後、インストールが完了して、無事webpacker.ymlができた。
DBの作成
- config/database.ymlの修正。環境変数から読んだりしたほうがいいのだろうけど、あとでやる。
default: &default ... username: root password: password ...
- DBの作成
% docker-compose run web rails db:create
起動
% docker-compose up
localhost:3000で無事アクセスできることを確認。
turbolinksの削除
SEOとか相当無難に行きたい案件なので、turbolinksは無効にする。
Gemfileから以下の箇所を削除
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks gem 'turbolinks', '~> 5'
- application.jsから以下の箇所を削除
require("turbolinks").start()
- application.html.erbを以下に変更
<%= stylesheet_link_tag 'application', media: 'all' %> <%= javascript_pack_tag 'application' %>
- docker-compose run web bundle updateを実行後、docker-compose buildを実行し直す。