LoginSignup
4
10

More than 3 years have passed since last update.

Ruby/Ruby on rails/MysqlをDockerで環境構築する方法

Last updated at Posted at 2019-05-29

DockerでRuby/Ruby on rails/mysqlの環境構築からデプロイまでできたのでメモしておきます。

(1)Dockerfile作成

Dockerfile


FROM ruby:2.5.3


RUN apt-get update -qq && \
    apt-get install -y build-essential \ 
                       libpq-dev \        
                       nodejs           

RUN mkdir /app_name 

ENV APP_ROOT /app_name 
WORKDIR $APP_ROOT

ADD ./Gemfile $APP_ROOT/Gemfile
ADD ./Gemfile.lock $APP_ROOT/Gemfile.lock


RUN bundle install
ADD . $APP_ROOT

(2)docker-compose.yml作成

docker-compose.yml
version: '3'
services:
  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: root
    ports:
      - "3306:3306"
    volumes:
      - .mysql-data:/var/lib/mysql
  web:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/app_name
    ports:
      - "3000:3000"
    links:
      - db

(3)Gemfile作成

Gemfile

source 'https://rubygems.org'
gem 'rails', '5.2.2'

Gemfile.lockも作成
$ touch Gemfile.lock

(4)新しいアプリを作成

$ docker-compose run web rails new  . --force --database=mysql --skip-bundle

databese.ymlを編集

database.yml
default: &default
  adapter: mysql2
  encoding: utf8
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password: password 
  host: db 

Gemfileをbundle install

$ docker-compose run web bundle install

(5)コンテナをビルドと起動

$ docker-compose build # コンテナをビルド

$ docker-compose up # コンテナの一斉起動

※bundle installの後にbuildする

(6)DB作成

$ docker-compose run web rails db:create

DBを作らないとエラーが出る

DBを作成後localhost:3000で初期画面が表示される!

()Herokuでデプロイ

herokuの登録,heroku cliはインストール済みとする

Herokuにアプリ作成

$ heroku create

データベースをMySQLに変更

$ heroku addons:add cleardb

ClearDBアドオンとは,ClearDBというデータベースサービスが提供している,MySQLを使うためのもの。

$ heroku config | grep CLEARDB_DATABASE_URL
mysql:// 〜 reconnect=trueがデータベース情報

mysqlの部分をmysql2に変更

環境変数を変更

$ heroku config:set DATABASE_URL=mysql2:// 〜 reconnect=true     //先ほどのデータベース情報全部
$ git add .
$ git commit -m "update for upload to heroku"

アプリをデプロイ

$ git push heroku master

マイグレーションファイル作成

$ heroku run rake db:migrate

参考

丁寧すぎるDocker-composeによるrails + MySQL on Dockerの環境構築

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