LoginSignup
0
0

More than 3 years have passed since last update.

DockerでRails環境構築

Last updated at Posted at 2021-03-23

① Docker関連のファイルを用意

Dockerfile

Dockerfile
# ベースイメージの指定
FROM ruby:2.7

# 必要なライブラリのインストール
RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - \
  && echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list \
  && apt-get update -qq \
  && apt-get install -y nodejs yarn 
#   作業ディレクトリの指定
WORKDIR /app
# ソース以下のファイルをコピー
COPY ./src /app
# rubyに必要なgemのインストール
RUN bundle config --local set path 'vendor/bundle' \
  && bundle install

docker-compose.yml

docker-compose.yml
version: '3'
# 管理するコンテナの記述
services:
  # データベース
  db:
    image: mysql:8.0
    # Mysqlの認証設定
    command: --default-authentication-plugin=mysql_native_password
    volumes:
    # ローカルのデータ:dockerのデータ 同期するための記述
      - ./src/db/mysql_data:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: password
  # rails
  web:
    # ディレクトリ直下のDockerfileを参照
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
    # ローカルのデータ:dockerのデータ 同期するための記述
      - ./src:/app
    ports:
    # ローカルのポート:dockerのポート
      - "3000:3000"
    depends_on:
    # Myaqlに接続するための記述
      - db

Gemfile

Gemfile
# railsのgemをインストールするための雛形
source 'https://rubygems.org'

gem 'rails','~> 6.1.0'

②Railsをインストール

terminal
rails_docker % docker-compose run web rails new . --force --database=mysql  // dbをmysqlに指定しrailsのインストール --force(強制的に実行オプション)
.
.
.
Webpacker successfully installed 🎉 🍰

③イメージをビルド

terminal
rails_docker % docker-compose build 

④新しく作成されたdatabase.ymlを編集

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

⑤データベースを作成

terminal
rails_docker % docker-compose run web rails db:create 

⑥起動

terminal
rails_docker % docker-compose up

スクリーンショット 2021-03-23 23.30.59.png

参考サイト

きよとのプログラミング大学

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