LoginSignup
2
2

More than 3 years have passed since last update.

docker-composeでRails6開発環境

Last updated at Posted at 2020-02-23

docker-composeでRails5.2開発環境に続いて、Rails6の環境も作ってみます。5.2から移行してくるとyarnとwebpackerがなかなか最初はややこしく感じます…。最下部に理由を書いていますが、alpine版のイメージをベースにしています。

必要なファイルは2つです。

docker-compose.yml
version: '3'
services:
  db:
    image: postgres
    volumes:
      - ./postgresql/data:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: "secret"
  web:
    build:
      context: .
      dockerfile: docker-web
    command: "rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/railsapp
    ports:
      - "3000:3000"
    depends_on:
      - db
docker-web
FROM ruby:2.6-alpine

RUN apk update && apk add libxml2-dev curl-dev make gcc libc-dev g++ nodejs \
  postgresql-client postgresql-dev tzdata yarn \
  && gem install rails -v "~> 6" -N

RUN mkdir /railsapp
WORKDIR /railsapp
# 後で有効化します
# COPY . /railsapp
# RUN bundle install && yarn install

まずは以下の手順で新しいプロジェクトを生成します。

docker-compose build
docker-compose run web rails new . --database=postgresql --skip-git

その後、上記Dockerfile内の最後の2行を有効化します。

COPY . /railsapp
RUN bundle install && yarn install

データベースの接続設定も修正が必要です。

railsapp/config/database.yml
host: db
username: postgres
password: secret

以下のコマンドを実行します。

docker-compose build
docker-compose up

あとは、いつもの手順でrailsの開発が開始できます!以下はデータベースを作成するコマンドです(docker-compose upをしたのと別のターミナルを立ち上げて実行します)。

docker-compose exec web rails db:create

Screen Shot 2020-02-23 at 13.45.51.png

docker-compose exec web rails g scaffold post title:string body:text published:boolean
docker-compose exec web rails db:migrate

ハマりどころ

ruby:2.6ruby:2.7のイメージを使ってみたところ、yarnのバージョンが適合せず動作しなかったため(下記エラー)、ruby:2.6-alpineイメージを使用しています。軽量さが特徴のようですが、逆に言うと、何か追加のgemを入れるたびにOS側のパッケージ追加が必要になるのが大変そうです…。

ArgumentError: Malformed version number string 0.32+git

初回のbundle installがかなり重たいのに、この手順だと2回それが走ることになり、待ち時間が長いです。もし最初から使えるGemfileが手元にあれば、それをrailsappに置いた状態でスタートすると速いです(公式の手順などで案内している方法)。

ある時点から?postgresqlのイメージがパスワードなしでは立ち上がらなくなりました(上記のサンプルは対応ずみのものです)。

PG::ConnectionBad
could not translate host name "db" to address: Name does not resolve

参考URL

2
2
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
2
2