16
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby on RailsAdvent Calendar 2019

Day 5

Ruby on Rails 6のDockerでの環境構築

Last updated at Posted at 2019-12-05

Ruby on Rails Advent Calendar 2019 5日目の記事になります。

Ruby on Rails 4.2のみ経験者でちょっと触れただけですが、3年ぶりくらいに環境構築してみました。
本当は環境構築だけじゃなくて弄くり回しかったところですが、環境構築だけでタイムアップでした。

【Rails】Rails 6.0 x Docker x MySQLで環境構築
zazk/Rails-6-Docker-Alpine
Quickstart: Compose and Rails
を大いに参考にさせていただきました。

環境

  • macOS Mojave
  • Docker for Mac
  • Ruby on Rails 6.0
  • PostgreSQL 11.1

初期状態のディレクトリ構成

.
├── Dockerfile
├── Gemfile
├── Gemfile.lock
├── entrypoint.sh
└── docker-compose.yml

Dockerfileの設定

FROM ruby:2.6
RUN 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 -qq \
    && apt-get install -y nodejs yarn \
    && mkdir /myapp
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
COPY . /myapp

COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

CMD ["rails", "server", "-b", "0.0.0.0"]

docker-compose.ymlの設定

docker-compose.yml
version: "3"
services:
  db:
    image: postgres:11.1-alpine
  web:
    build: .
    command: bundle exec rails server -b 0.0.0.0
    volumes:
      - ./:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - db

Gemfileの設定

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

Gemfile.lockの作成(空のファイル)

$ touch 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 "$@"

一旦Buildしてrails newでアプリ作成

$ docker-compose build
$ docker-compose run web rails new . --force --webpack --database=postgresql

再度Build

$ docker-compose build

./config/database.ymlの編集

database.yml



default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  host: db
  username: postgres

development:
  <<: *default
  database: postgres



docker-compose up を実行してサーバー立ち上げ

$ docker-compose up 

アクセス

0.0.0.0:3000にアクセスすると

Screenshot from Gyazo

苦戦したところとか

  • webpackerはyarn必須で辛い。というかyarnがないとそもそもサーバーすら立ち上がらないのか...
  • 依存関係が複雑すぎてbundle installでコケまくる
  • とりあえず公式ドキュメント読んだ方がいい。Alpine Linux難しい。

明日は@jkr_2255さんの記事です!

16
11
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
16
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?