rails6 docker mysql 環境構築
手順
各種ファイルの用意
rails new
イメージのビルド
database.yml の設定と DB 接続
コンテナ起動
各種バージョン
予め用意しておく
$ docker -v Docker version 19.03.13, build 4484c46d9d $ docker-compose -v docker-compose version 1.27.4, build 40524192 $ rails -v Rails 6.0.3.3 $ ruby -v ruby 2.7.1p83 (2020-03-31 revision a0c7c23c9c) [x86_64-darwin19] $ mysql --version mysql Ver 8.0.21 for osx10.15 on x86_64 (Homebrew)
ディレクトリ作成
必要なファイルを置くディレクトリを作成
$ mkdir myapp
ファイル作成
touch docker-compose.yml touch Gemfile touch Gemfile.lock touch Dockerfile touch entrypoint.sh
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 \
&& apt-get update -qq \
&& apt-get install -y nodejs yarn \
&& mkdir /myapp
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
COPY . /myapp
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"]
参考
RUNでyarnを入れる
https://classic.yarnpkg.com/en/docs/install#debian-stable
docker-compose.yml
version: '3'
services:
db:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: password
ports:
- '3316: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
Gemfile
source 'https://rubygems.org' gem 'rails', '~>6'
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 "$@"
参考
setコマンドの説明
【 set 】コマンド――シェルの設定を確認、変更する:Linux基本コマンドTips(205) - @IT
app作成
DBはmysql指定
あとでrspec入れたかったのでtestなし
webpacker入れる
$ docker-compose run web rails new . --force --no-deps --database=mysql --skip-test --webpacker
rails new で各種ファイルの作成
webpacker のインストールが完了したら、Gemfile が更新されているので、イメージをビルド
$ docker-compose build
mysqlのエラーが出たので以下の手順を踏んだ(出なければ飛ばす)
ld: library not found for -lssl
opensslのパスがビルドの時に必要
ビルドのときにLDFLAGSとかCPPFLAGSにパスを追加する必要がある
$ bundle config --local build.mysql2 "--with-ldflags=-L/usr/local/opt/openssl/lib" $ bundle install
参考
bundle installでmysql2がエラーになる件 - Qiita
config/database.ymlの編集
rails newで作成されてから
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
問題なければいまくいくはず
buildエラーCould not find bindex-0.8.1 in any of the sourcesが出た場合
キャッシュなしでbuildしなおしてからDB作成
10分くらいかかったと思う
$ docker-compose build --no-cache
参考
Dockerでコンテナ内にbundle installされない問題の解決法 - カクカクしかじか
docker をキャッシュを使わないでビルドする | ハックノート
コンテナ起動
$ docker-compose up
localhost:3000 にアクセス
リベースで起こった db/schema.rb のコンフリクト修正
内容
db/schema.rb
カラム追加したブランチをリベースしようとしたところで発生
<<<<<<< HEAD ActiveRecord::Schema.define(version: 20200513032325) do ======= ActiveRecord::Schema.define(version: 20200506032438) do >>>>>>> ブランチ名
最新のversionを選択した 次migrationする人がいれば、エラーが起きないように
で、修正
リベース続行
$ git rebase --continue db/schema.rb: needs merge You must edit all merge conflicts and then mark them as resolved using git add
修正したはずが、リベース が走らない。、 (エラー内容をちゃんと読んで、git add 使えば解決は早かったはず)
走らんやんけ、と思って、
[git] rebaseが完了できない現象("--continue"を飛ばしてしまったため)の解消手順 - Qiita この記事参考に--quitというオプションで、rebaseを中断しつつ、HEADは維持する形で進めてしまった
$ git rebase --quit
ブランチ確認
$ git branch * (HEAD detached from refs/heads/ブランチ)
実はHEADの扱い方を知らない、
detached HEADはこの記事を参考にしました
detached HEAD から脱出する方法を git の内部構造から探る - Qiita
ステータス確認
$ git status
HEAD detached from refs/heads/ブランチ
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: app/controllers/yyy/xxx_controller.rb
modified: app/views/yyy/xxx/index.html.slim
new file: db/migrate/20200506031358_zzz.rb
modified: db/seeds.rb
modified: spec/requests/yyy/xxx/zzz_spec.rb
Unmerged paths:
(use "git restore --staged <file>..." to unstage)
(use "git add <file>..." to mark resolution)
both modified: db/schema.rb
さっきも git add してよって書いてあったけ?とようやく気づく
db/schema.rb が git add されていないようです。
なので、してあげましょう
$ git add .
もう一度ステータス確認
$ git status
HEAD detached from refs/heads/ブランチ
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: app/controllers/yyy/xxx_controller.rb
modified: app/views/yyy/xxx/index.html.slim
new file: db/migrate/20200506031358_zzz.rb
modified: db/schema.rb
modified: db/seeds.rb
modified: spec/requests/yyy/xxx/zzz_spec.rb
よしよし、できてきた。
新しいブランチに移すのにgit stashを使った
参考 間違えてmasterで作業してしまった修正内容を別のブランチに移動させる方法 | ハックノート
修正内容を別の場所に一時保管します
$ git stash Saved working directory and index state WIP on (no branch): 2824bed2 最新のコミットメッセージ
ここでgit statusを行うと修正内容はなくなっているはずです
今回は新しいブランチに切り替える
$ git checkout -b 新ブランチ Switched to a new branch '新ブランチ'
さっき一時保管されていた内容を切り替えたブランチに適用
$ git stash apply
On branch 新ブランチ
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: db/migrate/20200506031358_zzz.rb
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: app/controllers/yyy/xxx_controller.rb
modified: app/views/yyy/xxx/index.html.slim
modified: db/schema.rb
modified: db/seeds.rb
modified: spec/requests/yyy/xxx/zzz_spec.rb
やっと戻って来れました。次回はすっきり対処したい
rails migrate直後でカラムの名前を変更したいとき
カラム追加したら名前を間違えた。
カラム追加からmigrateまで
マイグレーションファイル作成のコマンドはこんな感じ
$ rails g migration Addカラム名Toテーブル名 カラム名:データ型
20200506031358_ファイル名.rb
class Addカラム名Toテーブル名 < ActiveRecord::Migration[5.0]
def change
add_column :toilet, :jitaku_entered_at, :datetime, :after => :kaisya_entered_at
end
end
:after使えば、どのカラムの後ろにつけるか指定できて便利
migrateする
$ rails db:migrate
migrate取消
最新のmigrateがどこまでされているか確認
$ rails db:version Current version: 20200506031358
20200506031358まで、実行されている(今回migrateしたばかりのファイル)
次にmigrateを戻したいとこまでロールバックする(今回は一つ前まで)
$ rails db:rollback
複数のmigrationファイルのmigrateを取り消したいなら
$ rails db:rollback STEP=ファイル数
ファイル数にはそのまま数字を入れたらできます
migrateされていないファイルを確認
$ rails db:abort_if_pending_migrations
20200506031358がmigrarteされていませんってメッセージが来ます
migrationファイル修正、migrateし直す
migrationファイルの該当箇所を修正したら、、、
migrate実行
$ rails db:migrate
yarn devでCannot find module '@babel/compat-data/corejs3-shipped-proposals'と怒られた時の対処
エラー内容
yarn devでローカルサーバー立ち上げ
Cannot find module '@babel/compat-data/corejs3-shipped-proposals'
と怒られる
原因がわからん
本題とは関係ねえのだけれど、nuxtプロジェクトにgoogle analyticsを入れようとしたら謎のエラーが出てわちゃわちゃしてた
簡単に導入できるはずですけどね・・・
Nuxt.jsのプロジェクトでGoogleアナリティクスを導入する方法まとめ | オウンドメディア | 大阪市天王寺区SOHOホームページ制作 | デザインサプライ-DesignSupply.-
結論
力技ではあるが node_modules と yarn.lock を削除したことで解決
その後、yarn installで作り直してyarn devしたらいけた
おわり
git clone出来ない時にIPアドレスを変更した対処
エラー内容
$ git clone git@bitbucket.org:リモートリポジトリ Cloning into リモートリポジトリ... Forbidden fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.
ローカル環境に登録されたgitの登録内容とBitbucketに登録されたユーザ名とアドレスが、異なっていたので、とりあえず合わせてみることに。
$ git config --global user.name 旧ユーザ $ git config --global user.name “新ユーザ” $ git config --global user.name 新ユーザ $ git config --global user.email 旧アドレス $ git config --global user.email 新アドレス $ git config --global user.email 新アドレス
ここで再度git clone
$ git clone git@bitbucket.org:リモートリポジトリ Cloning into ‘リモートリポジトリ'... Warning: Permanently added the RSA host key for IP address ‘IPアドレスが書かれてる’ to the list of known hosts. Forbidden fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.
BitbucketのIPアドレスが変わった時に怒られるエラーぽい
参考になった記事たち
SSH接続でgit pushしたときに警告が出るやつへの対処法 - Qiita https://0371.blog/programming/bitbucket-git-push-ssh
解決
$ ssh-keygen -R '書かれていたIPアドレス'
作業ブランチを間違えてコミットしてしまった時の対処
developmentブランチで作業してたつもりが、masterブランチでコミットまでしてた。
経緯
コミットしてプッシュしたら
$ git push origin development Everything up-to-date
あれ?pushされない
ブランチ確認すると
$ git branch development * master
やってしもた
解決方法
$ git log
でコミット履歴を確認すると、今のブランチでcommitした、commit idが出てくる。それをコピー。
commit xxxxxxxxxxxxxxxxxxxxxxxの後ろのxxx...がcommit id
移動したいブランチに移動して
$ git cherry-pick コミットid
を叩く。これで正しいブランチにコミット完了。
最後にもう一度、正しいブランチにコミットできているか確認
$ git log
ちゃんとコミット履歴があった。
vagrant upできない
環境
mac OS catalina 10.15.3
virtualbox 6.0.14r133895
新しいmacが来たので、timemechineとハードディスクでデータ移行をした。 1日足らずで出来たし便利すぎる。
新しいmacでvagrant upしたら以下のエラー
Bringing machine ‘default’ up with ‘virtualbox’ provider... ==> default: Checking if box ‘centos/7’ version ‘1905.1’ is up to date... ==> default: Clearing any previously set network interfaces... There was an error while executing `VBoxManage`, a CLI used by Vagrant for controlling VirtualBox. The command and stderr is shown below. Command: [“hostonlyif”, “create”] Stderr: 0%... Progress state: NS_ERROR_FAILURE VBoxManage: error: Failed to create the host-only adapter VBoxManage: error: VBoxNetAdpCtl: Error while adding new interface: failed to open /dev/vboxnetctl: No such file or directory VBoxManage: error: Details: code NS_ERROR_FAILURE (0x80004005), component HostNetworkInterfaceWrap, interface IHostNetworkInterface VBoxManage: error: Context: “RTEXITCODE handleCreate(HandlerArg *)” at line 94 of file VBoxManageHostonly.cpp
virtualboxがおかしいことはわかった。
生存確認のため、バージョン確認
$ vagrant -v Vagrant 2.2.6 $ VBoxManage -v 6.0.14r133895
おる。移行前は動いていたのに
新バージョンの通知もきてたし、更新したら直るかなと思いやってみたがインストールも怒られた
結論
エラー画面残すの忘れたが参考リンクに同じ内容があった
VirtualBox製造元「Oracle」のDeveloper IDを承認してインストールやvagrant up出来るようにする方法
手順は
- Mac OSをシャットダウン
- Command(⌘)+ Rを押したたま起動
- Recovery modeになったら「Utilities」からTerminalを選択して起動
- OracleのDevelopper IDは 「VB5E2TV963」。 これを承認するために、下記コマンドを使う
$ spctl kext-consent add VB5E2TV963
enterで追加してMacを再起動
virtualboxのインストールとvagrant upができた。