LoginSignup
0
0

More than 1 year has passed since last update.

rails (apiモード)+ Docker + mysql 環境構築(メモ)

Last updated at Posted at 2021-05-11

はじめに

学習したことのメモとして書いていきます。

ディレクトリ構造

api/
 ├ Gemfile
 ├ Gemfile.lock
 ├ Dockerfile
 ├ docker-compose.yml 
 ├ entrypoint.sh 

Dockerfile dockercompose.yml Gemfile entrypoint.sh

Dockerfile
FROM ruby:2.7.4
RUN apt-get update

#最新版のyarnをインストールできるように設定
FROM ruby:2.7.4
RUN apt-get update

RUN set -x && curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \
  echo 'deb http://dl.yarnpkg.com/debian/ stable main' > /etc/apt/sources.list.d/yarn.list

RUN curl -sL https://deb.nodesource.com/setup_14.x | bash - && \
  apt-get install nodejs

RUN apt-get install -y \
  build-essential \
  libpq-dev \
  yarn
RUN mkdir /api
WORKDIR /api
COPY Gemfile  /api/
COPY Gemfile.lock /api/

RUN bundle install


COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

CMD ["rails", "server", "-b", "0.0.0.0"]

docker-compose.yml
version: '3'
services:
  api:
    build:
      context: ./api/
      dockerfile: Dockerfile
    volumes:
      - './api:/api'
    ports:
      - '8000:3000'
    tty: true
    stdin_open: true
    depends_on:
      - db
    links:
      - db
  db:
    image: mysql:5.7
    volumes:
      - ./db-data:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: root
    ports:
      - '3306:3306'

dbのvolume: について詳しくはこちらのブログ
volumeの場所についてはこちら

entrypoint.sh
#!/bin/bash
set -e

# Remove a potentially pre-existing server.pid for Rails.
rm -f /api/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', '~>6'

rails ファイルの作成

次にコマンドを実行します

docker-compose run --rm --api rails new . --api --force --database=mysql --skip-bundle --skip-test 

--skip-bundle : Dockerfileでbundle install するのでbundleをスキップ

--force : rails new で作られるファイルがすでに存在する場合上書き

--skip-test : rspecを使うのでスキップ

Gemfile が更新されたので下記を実行

docker-compose build

database.ymlの編集

またdatabase.ymlのデフォルトの部分を以下のように編集する

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

次に

docker-compose exec api rails db:create

docker-compose exec api rails db:migrate

これでdocker-compose up を行った後、指定したポート(今回は8000)でURL(localhost:8000)を入力すればよく見るrails の画面が現れる。

0
0
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
0
0