6
7

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.

Docker for Macを使ってRuby on Rails環境を構築する

Last updated at Posted at 2017-06-04

概要

Ruby on Railsの開発環境をDockerを使って簡単に構築したい。

Docker for Macのインストール

https://docs.docker.com/docker-for-mac/install/
からGet Docker for Mac [Stable]を選択しダウンロード、インストール。

Ruby on Rails + PostgreSQLのアプリを動かす

https://docs.docker.com/compose/rails/
に従う。

プロジェクトの構成を定義

適当なプロジェクトフォルダを作ってその中にファイルを4つ作る。

Dockerfile
FROM ruby:2.4.1
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN mkdir /myapp
WORKDIR /myapp
ADD Gemfile /myapp/Gemfile
ADD Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
ADD . /myapp
Gemfile
source 'https://rubygems.org' 
gem 'rails', '5.1.1'

空のGemfile.lockを作る。

Gemfile.lock
docker-compose.yml
version: '3'
services:
  db:
    image: postgres
  web:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - db

プロジェクトをビルド

ターミナルでプロジェクトフォルダに行き、以下を実行。

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

Railsのファイルがずらっと生成される。次に以下を実行。

docker-compose build

データベースの設定

config/database.ymldevelopment:の部分を以下のように変更。

config/database.yml
development: &default
  adapter: postgresql
  encoding: unicode
  database: myapp_development
  pool: 5
  username: postgres
  password:
  host: db

そしてデータベースを作成。

docker-compose run web rake db:create

起動

docker-compose up

http://localhost:3000
にアクセスしてみる。Yay! You’re on Rails!と表示されれば成功。

終了

Ctrl+Cで終了してしまうと次にdocker-compose upで起動しようとしたときにエラーで起動できなくなることがある。tmp/pids/server.pidが残ってしまっているのが原因なので、

rm tmp/pids/server.pid

で削除してから再びdocker-compose.upすればいい。ただ、毎回これをやるのは面倒なので、もう一つターミナルを立ち上げ、

docker-compose down

で終了すれば余計なファイルが残ったりせず、正常に終了できる。

DBの永続化

このままだとデータベースが終了するたび毎回消えてしまうので、docker-compose.ymlを以下のように修正する。

docker-compose.yml
version: '3'
services:
  db:
    restart: always
    image: postgres
    volumes:
      - sql-data:/var/lib/postgresql/data
  web:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - db
volumes:
  sql-data:
    driver: local
6
7
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
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?