LoginSignup
0
0

More than 3 years have passed since last update.

Rails6・Docker・MySQLによる環境構築

Last updated at Posted at 2021-04-03

無事環境構築できたものを自分用に備忘録として残しておく(適宜修正予定)

プラスでよく使うものも込みでまとめておく。
・Bootstrap導入
・Git / Heroku へPush

ファイル用意

ディレクトリを作成し、その中に以下のファイルを用意
Dockerfile
docker-compose.yml
Gemfile
Gemfile.lock
entrypoint.sh

これより以下のファイル内のmyappは自分が作成したディレクトリ名に置き換える

Dockerfile
FROM ruby:2.7.1

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

RUN apt-get update -qq && apt-get install -y nodejs yarn
RUN mkdir /myapp
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
COPY . /myapp

# 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"]

Rails5との変更点は、webpacker導入によるyarnnodeのインストール
credentials:editを使う予定の場合は、build時点で設定すると良さそう。
RUN apt-get install -y vim

Gemfile
source 'https://rubygems.org'
gem 'rails', '6.0.3'
Gemfile.lock
# 空のままで
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 "$@"
docker-compose.yml
version: '3'
services:
  db:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: password
    ports:
      - '3306:3306'
    command: --default-authentication-plugin=mysql_native_password
    volumes:
      - mysql-data:/var/lib/mysql
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - db
    stdin_open: true
    tty: true
volumes:
  mysql-data:
    driver: local

アプリ作成

このコマンドで最後webpackerがインストールされて完了

docker-compose run web rails new . --force --no-deps --database=mysql

Rspecを使用する予定の場合は、--skip-test

アプリ生成したら、buildする。最後Successfully ~~と出る

docker-compose build

DB作成

config/database.ymlを以下のように変更
また、ここまでの時点でmyappが適切に書き変わっているため、config/database.ymlでは修正する必要は無し。

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

development:
  <<: *default
  database: myapp_development

test:
  <<: *default
  database: myapp_test

production:
  <<: *default
  database: myapp_production
  username: myapp
  password: <%= ENV['MYAPP_DATABASE_PASSWORD'] %>

DBを作成する

docker-compose run web rake db:create
docker-compose run web rake db:migrate

Dockerを起動する

docker-compose up

http://localhost:3000 にアクセスし、お馴染みのページが表示されれば無事成功。

Bootstrap導入

必要なものをインストール(バージョンは指定しなくても。)

yarn add bootstrap@4.4.1 jquery@3.5.1 popper.js@1.16.1

config/webpack/environment.jsに追記

config/webpack/environment.js
const { environment } = require('@rails/webpacker')

const webpack = require('webpack')
environment.plugins.append('Provide', new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    Popper: ['popper.js', 'default']
}))

module.exports = environment

app/javascript/packs/application.jsに追記

app/javascript/packs/application.js
require("bootstrap/dist/js/bootstrap")

application.cssの拡張子cssをscssに変更

最後にapp/assets/stylesheets/application.scssに追記

app/assets/stylesheets/application.scss
/*
 *= require_tree .
 *= require_self
 */

@import "bootstrap/scss/bootstrap";

bootstrap jquery popper.jsをインストールしてから上記の記述だと、Herokuにデプロイした際にも適用された。


しかし以下のやり方だと、Herokuで適用されなかった。一応残しておく
インストールしたファイルをwebpackerの管理下に加える

app/javascript/packs/application.js
~省略~
import "bootstrap"
import "bootstrap/scss/bootstrap.scss"

正常に適用されているか確認するために、トップページを用意する。

rails g controller welcome index

ルーティングを設定

config/routes.rb
Rails.application.routes.draw do
  root "welcome#index"
end

viewを記述

app/views/layouts/application.html.erb
~省略~
  <body>
    <header class="navbar navbar-expand-sm navbar-light bg-light">
      <div class="container">
        <%= link_to "サービス名", root_path, class: "navbar-brand" %>
      </div>
    </header>
    <div class="container">
      <%= yield %>
    </div>
  </body>
</html>

適切に記述出来ていれば、bootstrapが適用される。

GitへPush

GitHubに登録している名前とメールアドレスを設定

git config --global user.name "自分の名前"
git config --global user.email "自分のメアド"

パスワード保持の時間設定(1日)

git config --global credential.helper "cache --timeout=86400"

Gitリポジトリ初期化

git init
git add -A
git commit -m "コミットメッセージ"

GitHubページで新規リポジトリ作成

そしてPushする

git remote add origin https://github.com/GitHubアカウント名/プロジェクト名.git
git push -u origin master

HerokuへPush(失敗談込み)

Herokuをインストールする。しかしここで問題発生。以前までCloud9で開発していたので、下のコマンドでインストールしていた。

source <(curl -sL https://cdn.learnenough.com/heroku_install)

そして上のコマンドを実行し、versionを確認すると、下のようになり上手くいかず。

heroku -v
/usr/local/heroku/bin/heroku: line 44: /usr/local/heroku/bin/node: cannot execute binary file

最終的には下記のように行いインストールに成功

まず、アンインストール

rm -rf /usr/local/heroku /usr/local/lib/heroku /usr/local/bin/heroku ~/.local/share/heroku ~/Library/Caches/heroku

次に以下のコマンドでインストール

brew tap heroku/brew && brew install heroku

そしてもう一度versionを確認

heroku -v
heroku/7.51.0 darwin-x64 node-v12.21.0

気をとりなおして、Herokuにログインする。

heroku login --interactive

アプリケーション作成

heroku create

Herokuにデプロイする

git push heroku master

アプリケーション名変更

heroku rename アプリケーション名

参考にした記事

https://qiita.com/me-654393/items/ac6f61f3eee66380ecd7
https://qiita.com/nsy_13/items/9fbc929f173984c30b5d
https://qiita.com/shingokubota/items/3562bf4996468899613c
https://qiita.com/take18k_tech/items/a36d77316e32a6696205

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