- 投稿日:2021-04-03T18:53:45+09:00
Rails6・Docker・MySQLによる環境構築
無事環境構築できたものを自分用に備忘録として残しておく(適宜修正予定) プラスでよく使うものも込みでまとめておく。 ・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導入によるyarnとnodeのインストール 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 アプリ生成したら、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: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
- 投稿日:2021-04-03T13:37:04+09:00
Mysql2::Error: Table ' ~~~~~ ' already existsと表示され他時の対処法
・マイグレーションしようとしたときにこのようなエラーが出た。 -- create_table(:microposts) rails aborted! StandardError: An error has occurred, all later migrations canceled: Mysql2::Error: Table 'microposts' already exists ~省略~ Caused by: ActiveRecord::StatementInvalid: Mysql2::Error: Table 'microposts' already exists ~省略~ Caused by: Mysql2::Error: Table 'microposts' already exists ~省略~ ・エラーの意味は「もうすでに同じテーブルがありますよ。」といった感じのエラー。 ・この状況になったらテーブルを消すことで解決する。 手順 ・rails dbでデータベースを開く。 ・mysqlが開くので、SHOW TABLES;を打ち込む。 ・上記の例のエラーに関するとmicropostsを消す事になるが、各々違うと思うので、臨機応変に対応。 drop table 〜〜〜;で消す。 ・削除ができたかどうかをSHOW TABLES;で確認。 ・exitで抜ける。 ・rails db:migrateを実行。 完
- 投稿日:2021-04-03T13:25:41+09:00
Rails 6.1・React・Docker・MySQLで環境構築
前書き 2021年3月からE2Eテストの自動化を担当し、初めて仕事でコードを書いている。 テスト対象のアプリケーションのapiがRails、フロントがReactで作られているので、 興味本意でプライベートで何か作ってみることにした。 (職場でテストコードをJSで書くので、JSに慣れるという意味合いもある。) 早速、Dockerで環境構築してみたので、備忘として残す。 環境 ・macOS Big Sur 11.2.3 ・Ruby 3.0 ・Rails 6.1.3.1 ・Docker 20.10.5 ・docker-compose 1.28.5 ・Mysql 8.0 手順 全体をざっくりと説明すると以下の通り。 1.ファイルを全て準備する 2.docker-compose buildする 3.railsとreactの各種コマンド実行 4.docker-compose upする 1.ファイルを全て準備する 最終的に、以下のような構造になる。 spa-chat |-- docker-compose.yml |-- api |-- entrypoint.sh |-- Gemfile |-- Gemfile.lock |-- Dockerfile |-- front |-- Dockerfile Rails関連 Gemfile Gemfile source 'https://rubygems.org' gem 'rails', '~>6' Gemfileには、使いたいRailsのバージョンを記入。 この場合、Rails6系の最新のバージョンを採用。 Gemfile.lock touch Gemfile.lock 空のGemfile.lockを作成。 entrypoint.sh 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 "$@" Dockerfile Dockerfile FROM ruby:3.0 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"] Dockerfileについては、Rails5系とRails6系で書き方が異なるので注意が必要。 Rails6系では、JavascriptコンパイラがWebpackerになったことに起因する。 React関連 Dockerfile Dockerfile FROM node:15.13.0-alpine RUN mkdir /myapp WORKDIR /myapp docker-compose.yml 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 api: build: ./api command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'" volumes: - ./api:/myapp - gem_data:/usr/local/bundle ports: - "3000:3000" depends_on: - db stdin_open: true tty: true front: build: ./front command: yarn start ports: - '8000:3000' volumes: - ./front:/myapp depends_on: - api volumes: mysql-data: gem_data: driver: local 2.docker-compose buildする 各種ファイルを揃えたので、イメージをbuild。 docker-compose build 3.RailsとReactの各種コマンド実行 コマンドを実行し、必要なファイルを揃えていく。 React ローカルで立ち上げる時と同じような感じで、以下のコマンドを実行。 docker-compose run front npx create-react-app front ※原因は突き止められなかったが、フロント用のDockerfileを置いたfrontディレクトリに、 さらに別のfrontディレクトリが作成され、その配下に各種フォルダが作成された。 なので、Dockerfileと同じ階層に、先程のコマンドで作成したフォルダを移動する必要がある。 (移動させないと、ブラウザからフロントにアクセスできない。) アドバイスいただけますと幸いです。 Rails まず、以下のコマンドを実行。 docker-compose run api rails new . --force --no-deps --database=mysql --skip-test --webpacker --api apiモードでrails new。 RSpecでテストコードを書くので、testディレクトリは作成しない。 次に、config/database.ymlを編集。 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'] %> そして、データベースを作成。 docker-compose run api rake db:create 4.docker-compose upする 準備が整ったので、コンテナを起動。 docker-compose up -d localhost:8000で見慣れたReactの画面が表示。 localhost:3000で見慣れたRailsの画面が表示。 参考にしたサイト https://qiita.com/nsy_13/items/9fbc929f173984c30b5d Rails側の設定を書くときにとても参考になりました。 https://nakatanorihito.com/programming/docker-rails-api-react-postgresql/ React側の記述や、ディレクトリ構造を参考にしました。 docker-compose.ymlは上記2サイトをどちらも参考にしています。 https://docs.docker.com/compose/rails/ docker docsに記載がある、Railsの環境構築方法。 Rails5系を使うことを前提に書かれている。
- 投稿日:2021-04-03T10:21:36+09:00
[Rails] ActiveRecord::ValueTooLong (Mysql2::Error: Data too long for column 'content' at row 1):
なぜこのエラーが出たか データ型の文字制限を超えた情報をDBに格納しようとしたから。 解決方法 データ型を変えることにした - t.string "content" + t.text "content" migrateした後は、DBにしっかり格納された。 補足: limitオプションでも条件を変えることができる。