LoginSignup
0
0

More than 1 year has passed since last update.

Docker で Ruby (2.7) on Rails (6.x) を立ち上げる (and 脱 Webpacker)

Last updated at Posted at 2021-06-02

はじめに

はじめまして。今のチームでイチから Rails を立ち上げなければいけなかったので、作業手順をメモとして残します。

Ruby 2.7 系、Rails 6 系です。
Webpacker は後々負債になることが多いので使いません 😡

事前準備

作業ディレクトリつくる

$ mkdir myapp 
$ cd myapp

Dockerfile つくる

2.7.3 を引っ張ってきます。

FROM ruby:2.7.3
RUN apt-get update -qq && apt-get install -y nodejs postgresql-client
RUN mkdir /myapp
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
COPY . /myapp

# 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 6 を引っ張ってきます。

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

Gemfile.lock つくる

勝手に内容吐き出されるので空で OK。

Gemfile.lock

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-compose.yml つくる

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:
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - db

上記のファイルの中で、以下の記載部分がないと Rails の起動時にエラーが出ます 🥺

docker-compose.yml
    environment:
      - POSTGRES_PASSWORD=password

Rails を立ち上げる

Rails のプロジェクトを生成する

$ docker-compose run web rails new . --force --no-deps --database=postgresql --skip-bundle --skip-javascript

--skip-javascript のオプションによって、デフォルトで入ってくる Webpacker の混入を防ぎます。

config/database.yml

生成された config/database.yml を以下の内容で上書きします。

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

bundle install する

$ docker-compose build

db を生成する

$ docker-compose run web rake db:create

立ち上げるっぺ

$ docker-compose up

環境のスクラップ & ビルドに便利なコマンドメモ

docker stop $(docker ps -q)
docker rm $(docker ps -q -a)
docker rmi $(docker images -q)
docker-compose run web rails new . --force --no-deps --database=postgresql --skip-bundle --skip-javascript

参考にさせていただいた記事

おしまい。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0