LoginSignup
4
6

More than 5 years have passed since last update.

docker-composeを使って手っ取り早くRailsアプリケーションを立ち上げる手順

Last updated at Posted at 2018-05-23

確認した環境

  • macOS 10.13.4
  • Docker for mac
$ docker version
Client:
 Version:       18.03.0-ce
 API version:   1.37
 Go version:    go1.9.4
 Git commit:    0520e24
 Built: Wed Mar 21 23:06:22 2018
 OS/Arch:       darwin/amd64
 Experimental:  false
 Orchestrator:  swarm

Server:
 Engine:
  Version:      18.03.0-ce
  API version:  1.37 (minimum version 1.12)
  Go version:   go1.9.4
  Git commit:   0520e24
  Built:        Wed Mar 21 23:14:32 2018
  OS/Arch:      linux/amd64
  Experimental: true

手順

適当な場所にディレクトリを用意(例えば ~/docker-rails)し、該当ディレクトリ配下で以下の手順を進める。

以下の内容で Dockerfile を用意

Dockerfile
# Dockerfile
FROM ruby:2.5
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN mkdir /myapp
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
COPY . /myapp

以下の内容でGemfileを用意(後述のrails newで上書きされる)

Gemfile
# Gemfile
source 'https://rubygems.org'
gem 'rails', '5.1.6'

空のGemfile.lockファイルを用意

$ touch Gemfile.lock

以下の内容で docker-compose.ymlを用意

docker-compose.yml
# docker-compose.yml
---
version: '3'
services:
  web:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"

rails new を実行する(--forceは既存のGemfileを書き換えるために必要)

$ docker-compose run web rails new . --force

すると、Gemfileが更新されRailsに必要な基本的なgemが登録される。

カレントディレクトリの内容が更新されているのでイメージビルドし直す。

$ docker-compose build

コンテナを起動する。

$ docker-compose up

ブラウザ等でhttp://localhost:3000/を開いて以下のように表示されればOK
image.png

参考: https://docs.docker.com/compose/rails/#connect-the-database

4
6
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
4
6