LoginSignup
5
8

More than 3 years have passed since last update.

【メモ】Rails APIモード × MySQL5.7 × Docker で環境構築

Last updated at Posted at 2019-10-23

はじめに

久しぶりにDockerを作成したら所々躓いたので要点をメモ

手順

  1. ディレクトリ用意&移動
  2. Gemfile, Gemfile.lock, Dockerfile, docker-compose.ymlを作成
  3. 2.のファイルにコード記述
  4. $ docker-compose build
  5. $ docker-compose run app rails new --api . --force --no-deps --database=mysql
  6. config/database.ymlを修正
  7. $ docker-compose build --no-cache
  8. $ docker-compose up
  9. $ docker-compose run app rails db:create

image.png

手順3, 6で用意するファイルについて

Gemfile
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

source "https://rubygems.org"
gem 'rails', '6.0.0'
Dockerfile
FROM ruby:2.6.5
ENV LANG C.UTF-8

# install required libraries
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs

RUN gem install bundler -v 2.0.2

# install bundler
RUN gem install bundler

WORKDIR /tmp
ADD Gemfile Gemfile
ADD Gemfile.lock Gemfile.lock
RUN bundle install

WORKDIR /app
COPY . /app
docker-compose.yml
version: '3'
services:
  mysql:
    image: mysql:5.7
    command: mysqld --character-set-server=utf8 --collation-server=utf8_general_ci
    ports:
      - "3306:3306"
    volumes:
      - mysql-data:/var/lib/mysql
    environment:
      MYSQL_DATABASE: app_development
      MYSQL_USER: root
      MYSQL_PASSWORD: password
      MYSQL_ROOT_PASSWORD: password
  app:
    tty: true
    stdin_open: true
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/app
    ports:
      - "3000:3000"
    depends_on:
      - mysql
volumes:
  mysql-data:
    driver: local
config/database.yml
default: &default
  adapter: mysql2
  encoding: utf8
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password: password
  host: mysql

development:
  <<: *default
  database: app_development

test:
  <<: *default
  database: app_test

# 一例です。productionについてはデプロイする際に注入する環境変数を適宜用意して下さい。
production:
  <<: *default
  username: <%= ENV['MYSQL_USER'] %>
  password: <%= ENV['MYSQL_ROOT_PASSWORD'] %>
  database: <%= ENV['MYSQL_DATABASE'] %>
  host: <%= ENV['MYSQL_HOST'] %>
  socket: <%= ENV['MYSQL_SOCKET'] %>
5
8
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
5
8