gotoshin

主に学んだ事の自分メモ用です。記事に書くまでも無いような事はhttps://scrapbox.io/study-diary/に書いてます。

dockerでRails×mysqlのAPI用環境構築 手順

どうやる?

Dockerfile作成

  • フォルダ名をapiへ変更
FROM ruby:2.5
RUN apt-get update -qq && apt-get install -y nodejs postgresql-client
RUN mkdir /api
WORKDIR /api
COPY Gemfile /api/Gemfile
COPY Gemfile.lock /api/Gemfile.lock
RUN bundle install
COPY . /api

# Add a script to be executed every time the container starts.
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

# Start the main process.
CMD ["rails", "server", "-b", "0.0.0.0"]

docker-compose.yml作成

  • dbのimageをmysql:5.7.21へ変更
  • valumesを./var/lib/mysqlへ変更
  • environmentでmysqlのユーザ・パスワードを設定
version: '3'
services:
  db:
    image: mysql:5.7.21
    volumes:
      - ./var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: root
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/api
    ports:
      - "3000:3000"
    depends_on:
      - db

entrypoint.sh作成

  • 公式と相違なし
#!/bin/bash
set -e

# Remove a potentially pre-existing server.pid for Rails.
rm -f /myapp/tmp/pids/server.pid

# Then exec the container's main process (what's set as CMD in the Dockerfile).
exec "$@"

Gemfile作成

  • 公式と相違なし
source 'https://rubygems.org'
gem 'rails', '~>5'

空のGemfile.lock作成

  • 公式と相違なし

rails new実行

  • --apiを追加
  • --databaseをmysqlへ変更
docker-compose run web rails new . --api --force --no-deps --database=mysql

docker-compose buildする

  • 公式と相違なし

database.ymlにpass追加

  • docker-compose.ymlで指定したpassを指定
  • hostをdbへ変更
default: &default
  adapter: mysql2
  encoding: utf8
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password: password
  host: db

データベースをcreateする

  • 公式と相違なし
docker-compose run web rake db:create

localhost:3000へアクセス

f:id:hatehate-nazenaze:20200210002652p:plain 完成!