20211224のRailsに関する記事は11件です。

Rails × Hasuraの共存環境を作ってみる

こんにちは! 気持ちは永遠の新卒1年目、いつの間にか3年目の株式会社エイチームコマーステック北村 (@NamedPython )です。 今日は、コマーステックがもしかしたら辿るかもしれない技術スタックを先行して検証していきます。 試す技術はタイトルにもある通り「Rails × Hasura」です。 役割分担としては、 Rails(API mode) マイグレーション ビジネスロジック Hasura GraphQL Engine 単純なCRUD ゲートウェイ スケジューラー みたいな感じにしたいな〜と想像しています。 シンプルなCRUDのGraphQLはHasuraにお任せ、複雑な処理はActionsでRailsに流したり、リゾルバを書いてRemote SchemasでHasuraに取り込んだりしてもいい。Railsでリゾルバを書くのが面倒なら別のバックエンドを立ててしまえばいい。これが実現できると、分厚くなりがちなRailsを徐々にマイクロにしていきつつ、他のスタックに移行するなり、Railsのアップグレードや改善に取り組める。という妄想をしているのです。 本当はMySQLなRails × HasuraのMySQL-previewな構成で試したかったんですが、IssueやDiscussionを見るにHasura社内の開発的にもMySQL対応の難易度が高いようで、公開されているもの↓は実用レベルになかったのでPostgreSQL構成で書いています。 環境をつくっていく それでは早速作っていきましょう。 以下のような構成を作ります。 プロジェクト構成 rails-hasura/ <- current, project dir ├ hasura │ └ config.yaml ├ rails │ ├ Dockerfile │ ├ Gemfile │ └ Gemfile.lock └ docker-compose.yaml ./rails/Gemfile、./rails/Dockerfile、./docker-compose.yaml、は以下です。 ./rails/Gemfile source 'https://rubygems.org' git_source(:github) { |repo| "https://github.com/#{repo}.git" } gem 'rails', '~> 6.1.4', '>= 6.1.4.4' ./rails/Dockerfile FROM ruby:2.6.5 RUN apt-get update && apt-get install -y \ build-essential \ libpq-dev \ nodejs \ default-mysql-client \ yarn WORKDIR /rails-app COPY Gemfile Gemfile.lock /rails-app/ RUN bundle install ./docker-compose.yml version: '3.8' services: rails: build: dockerfile: Dockerfile context: ./rails command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'" ports: - 3000:3000 volumes: - ./rails:/rails-app tty: true stdin_open: true hasura: image: hasura/graphql-engine:v2.1.1.cli-migrations-v3 ports: - 8080:8080 depends_on: - db restart: always environment: HASURA_GRAPHQL_DATABASE_URL: postgres://postgres:password@db:5432/postgres HASURA_GRAPHQL_ENABLE_TELEMETRY: 'false' HASURA_GRAPHQL_ENABLE_CONSOLE: 'true' HASURA_GRAPHQL_DEV_MODE: 'true' HASURA_GRAPHQL_ENABLED_LOG_TYPES: startup, http-log, webhook-log, websocket-log, query-log HASURA_GRAPHQL_UNAUTHORIZED_ROLE: anonymous HASURA_GRAPHQL_ADMIN_SECRET: devenvsecret db: image: postgres:12 restart: always volumes: - db_data:/var/lib/postgresql/data environment: POSTGRES_PASSWORD: password volumes: db_data: 続いて./hasura/config.yamlです。 version: 3 endpoint: http://localhost:8080/ admin_secret: devenvsecret enable_telemetry: false api_paths: v1_query: v1/query v2_query: v2/query v1_metadata: v1/metadata graphql: v1/graphql config: v1alpha1/config pg_dump: v1alpha1/pg_dump version: v1/version metadata_directory: metadata migrations_directory: migrations seeds_directory: seeds actions: kind: synchronous handler_webhook_baseurl: http://localhost:3000 codegen: framework: '' output_dir: '' さて、ここまで来たらあとはrails newの儀式です。 docker compose run rails rails new . --force --database=postgresql --skip-webpack-install そうすると、ガーっとファイルが生成され、bundle installなども実行されるので待ちます。Gemfile, Gemfile.lockの中身も書き変わりますよ。 続いては、./rails/config/database.ymlをいじる必要があるので、お好みのエディタで開き、次のように編集します。 ./rails/config/database.yml # PostgreSQL. Versions 9.3 and up are supported. # # Install the pg driver: # gem install pg # On macOS with Homebrew: # gem install pg -- --with-pg-config=/usr/local/bin/pg_config # On macOS with MacPorts: # gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config # On Windows: # gem install pg # Choose the win32 build. # Install PostgreSQL and put its /bin directory on your path. # # Configure Using Gemfile # gem 'pg' # default: &default adapter: postgresql encoding: unicode # For details on connection pooling, see Rails configuration guide # https://guides.rubyonrails.org/configuring.html#database-pooling pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + host: db + port: 5432 + username: postgres + password: password そうしましたらいよいよ起動でございます。 docker compose up --build -d # 起動ログを見たい方は docker compose logs -f こちらのコマンド実行もちょっとかかると思うので猫でも撫でてください Railsからのマイグレーションをしていく ...とその前に個人的な好みと、現行開発の方針的に顧客の目に触れそうな識別子はUUIDv4にしているので、Railsでそれができるようにしていく。 余談: RailsでUUIDv4なプライマリキー この手順を踏むと一瞬でPostgreSQLに依存するマイグレーションが走ったりしちゃうので注意されたし。 こちらの記事を参考にさせていただきました。インターネットに感謝 手順書こうかと思いましたが、ほぼ記事ままなので割愛。以下からは適用済みの前提があることをご認識ください。 rails g model -> rails db:migrate エイチームコマーステックですし、EC的にありきたりなテーブル構造を組みつつ、それがHasuraからどう認識されるかみてみましょう。一度に複数商品注文できるようにすると面倒なので、1注文1商品で。 お客さん customers 製品 products 注文 customer_orders 買ったお客さん customer_orders.customer_id -> customers.id 買った商品 customer_orders.product_id -> products.id docker compose exec rails bin/rails g model customer docker compose exec rails bin/rails g model product docker compose exec rails bin/rails g model customer_order ./rails/db/migrate/配下にできたそれぞれのファイルを以下のように編集! ./rails/db/migrate/#{timestamp}_create_customers.rb class CreateCustomers < ActiveRecord::Migration[6.1] def change create_table :customers, id: :uuid do |t| t.string :name, null: false t.string :email, null: false t.timestamps end end end ./rails/db/migrate/#{timestamp}_create_products.rb class CreateProducts < ActiveRecord::Migration[6.1] def change create_table :products, id: :bigint do |t| t.string :label_name, null: false t.integer :price, null: false, comment: 'tax excluded' t.string :description t.timestamps end end end ./rails/db/migrate/#{timestamp}_create_customer_orders.rb class CreateCustomerOrders < ActiveRecord::Migration[6.1] def change create_table :customer_orders, id: :uuid do |t| t.string :order_code, null: false t.datetime :sold_at, null: false, default: -> { 'CURRENT_TIMESTAMP' } t.references :customer, type: :uuid, foreign_key: true t.references :product, foreign_key: true t.integer :price, null: false t.integer :price_with_tax, null: false t.timestamps end end end そしていよいよマイグレーション実行〜 docker compose exec rails bin/rails db:migrate Hasuraで確認 さて続いてHasuraでどう認識されているかみてみましょう! 一旦見るだけなので http://localhost:8080/ から見ましょう。 おや、Enter admin-secretとありますね。大丈夫、まだ慌てる時間じゃありません。 ./docker-compose.ymlのhasuraサービス内の環境変数にHASURA_GRAPHQL_ADMIN_SECRETとして設定されている値を入力すればOKです(今回はdevenvsecret)。 続いての画面はGraphiQLですね。ここも使うんですが今見たいのは画像内のDATAタブです。 そして次もまたよくわからん画面が出るとは思いますが、続いてはpublicスキーマをポチー そうすると、こういった表示になるかと思います。 おや、赤枠内をみるとcustomer_ordersやcustomers、productsが見えますね。 他も見えてしまっていますが、これはActiveRecordのためのメタデータ保管庫でしょう。 Untracked tables or viewsとのことなので、まあHasura的に未追跡なんでしょう。 Trackのボタンを押してしまいたくなりますが、永続化できなくなってしまうのでReal consoleを立ち上げます。 Hasura CLIのインストールとReal consoleの立ち上げ 公式ドキュメントに従い、Hasura CLIをインストールしてください。筆者はHomebrewで入れました。 続いてこんな感じでコマンドをぽちぽち。 hasura --project hasura console すると、規定のブラウザで勝手にReal consoleが開きます。 「え、何が違うん?」と思うかもしれませんが、僕も見た目の違いはわかりません まあポートが違うのでそこで見分けてください。 このコンソールは、さっきの:8080なコンソールと違い、スキーマや設定に影響が出る変更をすると、設定ファイルとして吐き出され、永続化できます。 Hasuraでtrack、metadataの設定 さて、これで永続化される状態になったので、./hasura/下に吐かれるファイルをみつつテーブルをTrackしたり、リレーションを定義していきましょう。 テーブルのtrack さて、Hasuraにテーブルを認識してもらうために、Trackしましょう。 さっきと同じ手順で、DATAタブ > publicスキーマのところまでいきましょう。そして、見覚えのあった3つのテーブルのTrackボタンを押していきます。 まずはcustomersテーブル.... おお〜〜〜〜〜〜〜〜〜〜色々読み込まれとる〜〜〜〜〜〜〜〜! そしてファイルはどんな感じで吐かれているかというと...? め、めちゃくちゃ増えてる... そしてよく見てみると、今回Trackしたcustomersテーブルの名前がついたファイルがありますね(./hasura/metadata/databases/default/tables/public_customers.yaml)。 中身はどんな感じかというと...? table: name: customers schema: public おっ...、うん...。割とシンプルな感じですね。 まあTrackしただけならこんなもんなので、残りのテーブルもTrackしちゃいましょう。 左のツリーにはテーブルが増え、なにやら別種のUntracked ...も増えてきました。 どうやらこれは、外部キー制約をもとに判断した「これrelationships貼ったほうがいいんじゃないの?」というHasuraのレコメンデーションみたいです。 ざっと見ただけでも、 お客さんは注文をいっぱい持ってる customers -> [ customer_orders ] 製品はいっぱい注文されている products -> [ customer_orders ] 注文したお客さんを辿れる customer_orders -> customers 注文された製品を辿れる customer_orders -> products と列挙されているので、いい感じですね。賢いッ! リレーションのtrack せっかく上記のようにレコメンドが出ていますし、全部良さそうなのでTrack Allしちゃいましょう。 alert(...)で確認され、OKするとそのままレコメンドだけが消えて、完了のtipsが出ますね。 ファイルの変更を確認してみましょう。 ./hasura/metadata/databases/default/tables/public_customers.yaml table: name: customers schema: public + array_relationships: + - name: customer_orders + using: + foreign_key_constraint_on: + column: customer_id + table: + name: customer_orders + schema: public お〜、やはりリレーションが追加されるのもちゃんとファイルに吐かれますね。 テストデータを入れてGraphiQLで読み書きする さて、いよいよ下準備整ってきたので、ラストの検証します。 まずはテストデータですね。こんなところでしょうか。 customers name: NamedPython email: namedpython@namedpython.local allowed_to_send_emails: true products label_name: ゆずシトラスティー price: 390 description: パッションティーカスタムが美味しい customer_orders order_code: NAMED-ORDERCODE-123 customer_id: ↑ product_id: ↑ price: 390 price_with_tax: 429 テストコードは、Rails consoleでもいいですし、Hasura consoleでもできます。 後者でやるなら以下のような感じで入力画面にたどり着けます! 僕もこのタイミングで気づいたんですが、Rails製のcreated_at, updated_atはDB上にデフォルト値が設定されるわけではなくしかもNULL不可なので、後者でやる場合はcreated_at, updated_atもnow()で埋めてあげる必要があります。 ここはRails側のデフォルトのマイグレーション設定を書き換えてあげた方が良さそうなポイントですね。 テストデータを投入できたら早速クエリしてみましょう! これまで触ってきたDATAタブの左側、APIタブを開きましょう! いつの間にか、ここにもいろいろできていますね。 では単純なところから行ってみましょうか。 query ShowProductInformations { products { id label_name price description } } お〜取得できましたね〜! そしたらこういうのはどうですかね? query ShowCustomersProfileAndOrders { customers { id name email customer_orders { order_code price_with_tax product { label_name price } } } } お〜、has_many / has_oneな関係もちゃんとGraphQLでとれてますね!!!! さて、GraphQLがいい感じに叩けるのがわかったところで、今回の検証は以上にしようと思います。 実は他にもEnumだったりComputed Fieldsだったりの検証もしたかったんですが、それはまた別の機会に おわりに + We're hiring! ここまで読んでいただいてありがとうございました! 株式会社エイチームコマーステックには、僕みたいな新しいモノ好きがこういったことに挑戦できる土壌があり、そういった環境で「Eコマースを面白くしていきたいぜ」という方を募集しています 「ちょっとお話聞いてみたいぞ!」だったり、「Rails/Hasuraどんな感じで使ってるんだ?」が気になる方は、Twitter(@NamedPython)のDMやリプライまでお気軽にお声がけください! コマーステックのコーポレートサイトや、採用ページもチェックしてみてくださいね! それでは良い年末年始をお過ごしください!
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Dockerで実装しているテーブルの内容をターミナルで確認する方法(rails)

備忘録として Dockerを使ってrailsのアプリケーション実装をしている時に、 テーブルの更新内容を確認したくなったので調べた内容を記録しています。 方法 % docker-compose run web rails db 上記のコマンドを入力すると ターミナルに下記内容が表示されます psql (13.5 (Debian 13.5-0+deb11u1), server 14.1 (Debian 14.1-1.pgdg110+1)) WARNING: psql major version 13, server major version 14. Some psql features might not work. Type "help" for help. ○○_development=# #の後に \d テーブル名; と打てばテーブル詳細が表示されます。 ex: \d users; と入力すれば Table "public.users" Column | Type | Collation | Nullable | Default ------------------------+--------------------------------+-----------+----------+----------------------------------- id | bigint | | not null | nextval('users_id_seq'::regclass) first_name | character varying | | not null | ''::character varying last_name | character varying | | not null | ''::character varying first_name_kana | character varying | | not null | ''::character varying last_name_kana | character varying | | not null | ''::character varying email | character varying | | not null | ''::character varying encrypted_password | character varying | | not null | ''::character varying Indexes: "users_pkey" PRIMARY KEY, btree (id) "index_users_on_email" UNIQUE, btree (email) "index_users_on_reset_password_token" UNIQUE, btree (reset_password_token) Referenced by: TABLE "orders" CONSTRAINT "fk_rails_f868b47f6a" FOREIGN KEY (user_id) REFERENCES users(id) みたいな感じで表示されて確認できます。  終了方法 ○○_development=# \q で抜けることができます!! 最後に 調べていた記事には PostgreSQL利用時の操作になる と記載がありました!!Mysqlではできないのかもしれません。 備忘録として書きましたが誰かの為になることがあれば幸いです!!
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

RailsでDDDのバリューオブジェクトを実装してみる

この記事は何 DDDを学んだ事がある方は「バリューオブジェクト」という名前を一度は聞いた事があるのではないでしょうか・ この記事ではRailsでバリューオブジェクトを実装するならどのような実装にすると良さそうかを紹介します。 なお、バリューオブジェクトの具体的な実装方針は千差万別だと思うので、この記事で紹介する実装はあくまで一例だと思っていただけるとありがたいです。 具体的なバリューオブジェクトの解説は↓の記事などが参考になると思います。 バリューオブジェクトの条件 バリューオブジェクトは以下の条件を満たしている必要があります。 条件は以下の通りです。 オブジェクトはイミュータブルである 値の変化はインスタンスの再生成で実現する オブジェクトの同一生はバリューオブジェクトが持つattributeの一致で定義される Railsで実装する際も、これらの条件を満たす必要があります。 そしてバリューオブジェクトとして実装する以上、バリデーションも行えるようにしたいです。 これらの要件を満たすインターフェースを実装してみます。 実装物 実装物はズバリ↓のようなクラスです。 class Value::Base include ActiveModel::Model def initialize fail ActiveRecord::RecordInvalid unless valid? end # @param other [::Value::Base] # @return [true, false] def ==(other) evaluate_attributes.all? { |variable| try(variable) == other.try(variable) } end private # @return [Array<String>] attributes used to equal evaluation def evaluate_attributes fail NotImplementedError end end このクラスは以下のように継承し、利用します。 class Value::Name < Value::Base attr_reader :first_name, :last_name validates :first_name, presence: true validates :last_name, presence: true def initialize(first_name:, last_name:) @first_name = first_name @last_name = last_name super() end def full_name "#{first_name} #{last_name}" end private # @note Override {::Value::Base#evaluate_attributes} def evaluate_attributes %i(first_name last_name) end end このクラスの機能について説明します。 オブジェクトの不変性 このクラスでは、基本的にsetterを提供せずに、getterのみを公開します。 こうすることで、外部からインスタンスの変更を行うことはできません。 オブジェクトの同一性 このクラスにはevaluate_attributesというメソッドを実装しています。 また、==メソッドをオーバーライドし、各attributesの値の同一性を検証することでオブジェクト自体の同一性を判定するようにしています。 このようにすることで、==メソッドを用いた同一性検証はバリューオブジェクトが満たすべき条件と同じになります。 値のバリデーション このクラスではActiveModel::Modelモジュールをincludeしています。 また、initializeのタイミングでvalid?がfalseを返すときにエラーを返すようになっています。 このように実装をし、子クラスで最後にsuper()を実行することで、インスタンス生成時に検証まで行えるようになっています。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Docker上のyarnの依存関係を解決。

docker-compose upで RUN yarn upgrade の部分でエラーがでた。 Step 13/19 : RUN yarn upgrade ---> Running in 3c8f3922483b yarn upgrade v1.22.17 warning package-lock.json found. Your project contains lock files generated by tools other than Yarn. It is advised not to mix package managers in order to avoid resolution inconsistencies caused by unsynchronized lock files. To clear this warning, remove package-lock.json. [1/4] Resolving packages... info There appears to be trouble with your network connection. Retrying... warning @rails/webpacker > webpack > watchpack > watchpack-chokidar2 > chokidar@2.1.8: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies. warning @rails/webpacker > webpack > watchpack > watchpack-chokidar2 > chokidar > fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2. warning @rails/webpacker > postcss-preset-env > postcss-color-functional-notation > postcss-values-parser > flatten@1.0.3: flatten is deprecated in favor of utility frameworks such as lodash. warning @rails/webpacker > webpack > node-libs-browser > url > querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead. warning @rails/webpacker > optimize-css-assets-webpack-plugin > cssnano > cssnano-preset-default > postcss-svgo > svgo@1.3.2: This SVGO version is no longer supported. Upgrade to v2.x.x. warning @rails/webpacker > webpack > micromatch > snapdragon > source-map-resolve > resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated warning @rails/webpacker > webpack > micromatch > snapdragon > source-map-resolve > urix@0.1.0: Please see https://github.com/lydell/urix#deprecated [2/4] Fetching packages... error @npmcli/fs@1.1.0: The engine "node" is incompatible with this module. Expected version "^12.13.0 || ^14.15.0 || >=16". Got "10.24.0" error Found incompatible module. info Visit https://yarnpkg.com/en/docs/cli/upgrade for documentation about this command. The command '/bin/sh -c yarn upgrade' returned a non-zero code: 1 ERROR: Service 'web' failed to build : Build failed warning package-lock.json found. Your project contains lock files generated by tools other than Yarn. It is advised not to mix package managers in order to avoid resolution inconsistencies caused by unsynchronized lock files. To clear this warning, remove package-lock.json. It is advised not to mix package managers in order to avoid resolution inconsistencies caused by unsynchronized lock files. そのとおりでしかないので、package-lock.jsonを消した。npmとyarnを混在させてた。packge.jsonをどっちも使うから互換性あると思ってたが、lockファイルはまた別の話か。 The engine “node” is incompatible with this module が核となる部分か。 error @npmcli/fs@1.1.0: The engine "node" is incompatible with this module. Expected version "^12.13.0 || ^14.15.0 || >=16". Got "10.24.0" nodeのバージョンが古いと怒られてる気がする node -v v16.13.1 ローカルではこうだったが、docker上では Got "10.24.0"となってるので 16系のnodeをインストールするDockerfileを記述したい。 Dockerfileにこのように記述してみた。 RUN curl -sL https://deb.nodesource.com/setup_16.x | bash - && \ #←ここ変更 apt-get install -y nodejs  docker-compose upを実行。 ├─ wrap-ansi@5.1.0 ├─ ws@8.4.0 ├─ xtend@4.0.2 ├─ yaml@1.10.2 ├─ yargs-parser@13.1.2 ├─ yargs@13.3.2 ├─ yocto-queue@0.1.0 └─ youtube-player@5.5.2 Done in 116.92s. RUN yarn upgrade を突破した!!!やったぜ!! s:46 webpacker_1 | return func(...args); webpacker_1 | ^ webpacker_1 | webpacker_1 | TypeError: Class constructor ServeCommand cannot be invoked without 'new' webpacker_1 | at runWhenInstalled (/coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:46:9) webpacker_1 | at promptForInstallation (/coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:140:10) webpacker_1 | at /coffee_passport/node_modules/webpack-cli/bin/cli.js:32:43 webpacker_1 | at Object.<anonymous> (/coffee_passport/node_modules/webpack-cli/bin/cli.js:366:3) webpacker_1 | at Module._compile (node:internal/modules/cjs/loader:1101:14) webpacker_1 | at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) webpacker_1 | at Module.load (node:internal/modules/cjs/loader:981:32) webpacker_1 | at Function.Module._load (node:internal/modules/cjs/loader:822:12) webpacker_1 | at Module.require (node:internal/modules/cjs/loader:1005:19) webpacker_1 | at require (node:internal/modules/cjs/helpers:102:18) coffee_passport_webpacker_1 exited with code 1 しかしwebpackerコンテナはこのようになってた。。 依存関係がやばいからだとおもうので、過去の自分の記事を参考に https://qiita.com/divclass123/items/5cee396071540256e11e Dockerfileに RUN yarn upgrade-interactive --latest これをついか。 この記事のように、このコマンドは対話型で、依存関係を直していくので、 RUN yarn upgrade-interactive --latest このコマンド書くだけでは不十分なのではないか。 実際自分がローカルで、yarn upgrade-interactive --latestを叩いたときには 対話型の画面になって、aを押した後にエンターを押した。 RUN a RUN enter とドッカーファイルに書くことができればいいのだが。。。 もしくは、COPY . /coffee_passport でキャッシュが使われてる気がするので、 ローカルで依存を直しても、依存を直す以前のディレクトリがコピーされていたら全く意味がないので docker-compose build --no-cache を実行する必要があるのではないか。 Step 15/21 : RUN yarn upgrade-interactive --latest ---> Running in 5330c7208d1b yarn upgrade-interactive v1.22.17 success All of your dependencies are up to date. Done in 6.03s. とdocker-composeのログをみたらなっていた。 つまり RUN yarn upgrade-interactive --latest 単体でも機能していた。 これで依存関係が治ればいいのだが、、。。。 Recreating coffee_passport_webpacker_1 ... error ERROR: for coffee_passport_webpacker_1 cannot stop container: d0dea180963dc92a187a59c4a4Recreating coffee_passport_web_1 ... error xit event ERROR: for coffee_passport_web_1 cannot stop container: a07b86322e13b4796550a99f01af6c0fd4a2279a3f05e5b210eb06cd0a171c57: tried to kill container, but did not receive an exit event ERROR: for webpacker cannot stop container: d0dea180963dc92a187a59c4a462dfebc52a85d5071cfec4ef746f162dd59009: tried to kill container, but did not receive an exit event ERROR: for web cannot stop container: a07b86322e13b4796550a99f01af6c0fd4a2279a3f05e5b210eb06cd0a171c57: tried to kill container, but did not receive an exit event ERROR: Encountered errors while bringing up the project. 依存関係とは別のエラーがでた。。。一旦dockerをまっさらにして、やり直そう。 コンテナが止まらないので、再起動。 すべてのネットワークと、ボリューム、コンテナを削除できた。 docker-compose build --no-cache を実行。 --no-cacheつける意味ない気がするが念には念を くそほど、長くロードされてる。 ---> 69212fdb637b Successfully built 69212fdb637b Successfully tagged coffee_passport_webpacker:latest Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them と一旦ビルドは成功。 docker-compose up を実行。 [24] ./app/javascript/packs/components/about_coffee_passport.vue + 2 modules 3.2 KiB {3} {11} {12} {14} [built] | 3 modules [25] ./app/javascript/packs/components/contact.vue + 2 modules 1.74 KiB {4} {11} {12} {14} [built] | 3 modules [49] ./app/javascript/packs/router/router.js 469 bytes {11} {12} {14} [built] [52] ./app/javascript/packs/components/static_pages/appExplain.vue + 4 modules 5.41 KiB {0} {9} [built] | 5 modules [53] ./app/javascript/packs/components/footer.vue + 2 modules 1.16 KiB {6} {11} [built] | 3 modules [60] ./app/javascript/packs/tag.js 5.77 KiB {1} {15} [built] [61] ./app/javascript/packs/preview.js 2.77 KiB {1} {13} [built] [64] ./app/javascript/packs/app_explain.js 329 bytes {0} [built] [65] ./app/javascript/packs/application.js 911 bytes {1} [built] [74] ./app/javascript/packs/footer.js 192 bytes {11} [built] [89] ./app/javascript/packs/hello_vue.js + 5 modules 9.73 KiB {12} [built] | ./app/javascript/packs/hello_vue.js 2.19 KiB [built] | ./app/javascript/app.vue 552 bytes [built] | ./app/javascript/app.vue?vue&type=template&id=286cd28a&scoped=true& 213 bytes [built] | ./app/javascript/app.vue?vue&type=script&lang=js& 364 bytes [built] | ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./app/javascript/app.vue?vue&type=template&id=286cd28a&scoped=true& 3.95 KiB [built] | ./node_modules/babel-loader/lib??ref--7-0!./node_modules/vue-loader/lib??vue-loader-options!./app/javascript/app.vue?vue&type=script&lang=js& 2.44 KiB [built] [90] ./app/javascript/packs/components/Home.vue + 2 modules 826 bytes {2} [built] | 3 modules + 76 hidden modules こんな感じでコンパイルも成功してそう。 だし、docekr-compose up成功してくれ、、、 webpacker_1 | /coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:46 webpacker_1 | return func(...args); webpacker_1 | ^ webpacker_1 | webpacker_1 | TypeError: Class constructor ServeCommand cannot be invoked without 'new' webpacker_1 | at runWhenInstalled (/coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:46:9) webpacker_1 | at promptForInstallation (/coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:140:10) webpacker_1 | at /coffee_passport/node_modules/webpack-cli/bin/cli.js:32:43 webpacker_1 | at Object. (/coffee_passport/node_modules/webpack-cli/bin/cli.js:366:3) webpacker_1 | at Module._compile (node:internal/modules/cjs/loader:1101:14) webpacker_1 | at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) webpacker_1 | at Module.load (node:internal/modules/cjs/loader:981:32) webpacker_1 | at Function.Module._load (node:internal/modules/cjs/loader:822:12) webpacker_1 | at Module.require (node:internal/modules/cjs/loader:1005:19) webpacker_1 | at require (node:internal/modules/cjs/helpers:102:18) coffee_passport_webpacker_1 exited with code 1 だめだぁ。。。・・・・ reating coffee_passport_db_1 ... done Creating coffee_passport_selenium_chrome_1 ... done Creating coffee_passport_webpacker_1 ... done Creating coffee_passport_web_1 ... done Attaching to coffee_passport_db_1, coffee_passport_webpacker_1, coffee_passport_web_1 db_1 | 2021-12-23 15:14:49+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.21-1debian10 started. db_1 | 2021-12-23 15:14:49+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql' db_1 | 2021-12-23 15:14:49+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.21-1debian10 started. db_1 | 2021-12-23 15:14:49+00:00 [Note] [Entrypoint]: Initializing database files db_1 | 2021-12-23T15:14:49.935688Z 0 [System] [MY-013169] [Server] /usr/sbin/mysqld (mysqld 8.0.21) initializing of server in progress as process 44 db_1 | 2021-12-23T15:14:49.944995Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started. db_1 | 2021-12-23T15:14:50.495413Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended. db_1 | 2021-12-23T15:14:52.240716Z 6 [Warning] [MY-010453] [Server] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option. webpacker_1 | /coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:46 webpacker_1 | return func(...args); webpacker_1 | ^ webpacker_1 | webpacker_1 | TypeError: Class constructor ServeCommand cannot be invoked without 'new' webpacker_1 | at runWhenInstalled (/coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:46:9) webpacker_1 | at promptForInstallation (/coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:140:10) webpacker_1 | at /coffee_passport/node_modules/webpack-cli/bin/cli.js:32:43 webpacker_1 | at Object.<anonymous> (/coffee_passport/node_modules/webpack-cli/bin/cli.js:366:3) webpacker_1 | at Module._compile (node:internal/modules/cjs/loader:1101:14) webpacker_1 | at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) webpacker_1 | at Module.load (node:internal/modules/cjs/loader:981:32) webpacker_1 | at Function.Module._load (node:internal/modules/cjs/loader:822:12) webpacker_1 | at Module.require (node:internal/modules/cjs/loader:1005:19) webpacker_1 | at require (node:internal/modules/cjs/helpers:102:18) coffee_passport_webpacker_1 exited with code 1 db_1 | 2021-12-23 15:14:55+00:00 [Note] [Entrypoint]: Database files initialized db_1 | 2021-12-23 15:14:55+00:00 [Note] [Entrypoint]: Starting temporary server db_1 | 2021-12-23T15:14:55.874976Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.21) starting as process 91 db_1 | 2021-12-23T15:14:55.894098Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started. db_1 | 2021-12-23T15:14:56.143204Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended. db_1 | 2021-12-23T15:14:56.253183Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: /var/run/mysqld/mysqlx.sock db_1 | 2021-12-23T15:14:56.401692Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed. db_1 | 2021-12-23T15:14:56.402164Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel. db_1 | 2021-12-23T15:14:56.407071Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory. db_1 | 2021-12-23T15:14:56.434607Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.21' socket: '/var/run/mysqld/mysqld.sock' port: 0 MySQL Community Server - GPL. db_1 | 2021-12-23 15:14:56+00:00 [Note] [Entrypoint]: Temporary server started. db_1 | Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it. db_1 | Warning: Unable to load '/usr/share/zoneinfo/leap-seconds.list' as time zone. Skipping it. db_1 | Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it. db_1 | Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it. db_1 | db_1 | 2021-12-23 15:14:59+00:00 [Note] [Entrypoint]: Stopping temporary server db_1 | 2021-12-23T15:14:59.658326Z 10 [System] [MY-013172] [Server] Received SHUTDOWN from user root. Shutting down mysqld (Version: 8.0.21). db_1 | 2021-12-23T15:15:01.954163Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.21) MySQL Community Server - GPL. db_1 | 2021-12-23 15:15:02+00:00 [Note] [Entrypoint]: Temporary server stopped db_1 | db_1 | 2021-12-23 15:15:02+00:00 [Note] [Entrypoint]: MySQL init process done. Ready for start up. db_1 | db_1 | 2021-12-23T15:15:02.932785Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.21) starting as process 1 db_1 | 2021-12-23T15:15:02.943118Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started. db_1 | 2021-12-23T15:15:03.122522Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended. db_1 | 2021-12-23T15:15:03.216008Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock db_1 | 2021-12-23T15:15:03.332617Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed. db_1 | 2021-12-23T15:15:03.332862Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel. db_1 | 2021-12-23T15:15:03.336670Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory. db_1 | 2021-12-23T15:15:03.357237Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.21' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server - GPL. しかもwebコンテナがdoneになってるのにログに表示されないし localhost:3000も受け付けてくれない。 このページは動作してませんとなる・ soichirohara@SoichironoMacBook-Pro coffee_passport % docker-compose ps Name Command State Ports coffee_passport_db_1 docker-entrypoint.sh --def Up 0.0.0.0:3306->3306/tcp, ... 33060/tcp coffee_passport_selenium_ch /opt/bin/entry_point.sh Up 4444/tcp, 5900/tcp rome_1 coffee_passport_web_1 entrypoint.sh ./bin/rails Up 0.0.0.0:3000->3000/tcp ... coffee_passport_webpacker_1 entrypoint.sh ./bin/webpac Exit 1 ... coffee_passport_web_1 コンテナ立ち上がってるはずなのに。。。 coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:46 return func(...args); ^ TypeError: Class constructor ServeCommand cannot be invoked without 'new' at runWhenInstalled (/coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:46:9) at promptForInstallation (/coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:140:10) at /coffee_passport/node_modules/webpack-cli/bin/cli.js:32:43 at Object.<anonymous> (/coffee_passport/node_modules/webpack-cli/bin/cli.js:366:3) at Module._compile (node:internal/modules/cjs/loader:1101:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Module.require (node:internal/modules/cjs/loader:1005:19) at require (node:internal/modules/cjs/helpers:102:18) webpackerコンテナ全体のログはこんな感じ TypeError: Class constructor ServeCommand cannot be invoked without 'new' をググったら。 これは今のところうまくいきました。package.jsonファイルのwebpack-dev-serverバージョンを次のように変更します。 "webpack-dev-server": "~3" そして、yarn installまたはを実行しnpm installます。 ソース:https://stackoverflow.com/a/69050300/2774342 PSこれは一時的な解決策になる可能性がありますが、新しいバージョンがリリースされるため、将来の参照(数か月後だと思います)のために、この回答は非推奨になります。 とかいてあったので webpack-dev-serverをバージョン3のままにする これを行うには、package.jsonファイルを更新します。 package.json "webpack-dev-server": "~3" をこうする。 - RUN bundle exec rails webpacker:compile - RUN yarn upgrade-interactive --latest をけした。コンパイル専用のコンテナがあるので、わざわざDockerfileに記述しなくてもいいとおもった。 RUN yarn upgrade-interactive --latest は "webpack-dev-server": "~3"とバージョンを固定したいので、 アップデートをしてしまうコマンドを削除 RUN yarn install --check-files を追記 docker-compose up で成功!! やったぜ!! 上手く言ったdockerfileとdocker-compose.yml FROM ruby:2.6.5 ## nodejsとyarnはwebpackをインストールする際に必要 # yarnパッケージ管理ツールをインストール RUN curl http://deb.debian.org/debian/dists/buster/main/binary-amd64/by-hash/SHA256/935deda18d5bdc25fb1813d0ec99b6e0e32a084b203e518af0cf7dc79ee8ebda | head RUN apt-get update && apt-get install -y curl apt-transport-https wget && \ 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 && apt-get install -y yarn && apt-get install -y graphviz RUN curl -sL https://deb.nodesource.com/setup_16.x | bash - && \ apt-get install -y nodejs # chromeの追加 RUN apt-get update && apt-get install -y unzip && \ CHROME_DRIVER_VERSION=`curl -sS chromedriver.storage.googleapis.com/LATEST_RELEASE` && \ wget -N http://chromedriver.storage.googleapis.com/$CHROME_DRIVER_VERSION/chromedriver_linux64.zip -P ~/ && \ unzip ~/chromedriver_linux64.zip -d ~/ && \ rm ~/chromedriver_linux64.zip && \ chown root:root ~/chromedriver && \ chmod 755 ~/chromedriver && \ mv ~/chromedriver /usr/bin/chromedriver && \ sh -c 'wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -' && \ sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list' && \ apt-get update && apt-get install -y google-chrome-stable RUN /bin/sh -c /bin/sh -c bundle update --bundler RUN gem install bundler:2.1.4 RUN mkdir /coffee_passport WORKDIR /coffee_passport COPY . /coffee_passport COPY Gemfile /coffee_passport/Gemfile COPY Gemfile.lock /coffee_passport/Gemfile.lock # RUN bundle update rails # RUN bundle update # RUN bundle update mimemagic # RUN bundle update capybara selenium-webdriver #RUN bundle update nokogiri marcel mimemagic RUN bundle install RUN yarn upgrade #RUN yarn upgrade-interactive --latest #RUN bundle exec rails webpacker:comp RUN yarn install --check-files # 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"] docker-compose.yml version: '3' services: db: image: mysql:8.0.21 cap_add: - SYS_NICE # コンテナにLinux機能を追加するオプションのようです。SYS_NICEは、プロセスの優先度(nice値)をあげます。 environment: MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} MYSQL_HOST: db ports: - '3306:3306' volumes: - mysql-data:/var/lib/mysql command: --default-authentication-plugin=mysql_native_password # 認証方式を8系以前のものにする web: &web build: . command: ./bin/rails s -b 0 stdin_open: true tty: true # この2文を追加でコンテナ内の標準入出力をローカルマシンのターミナルにアタッチする準備が整います。 volumes: - .:/coffee_passport ports: - "3000:3000" depends_on: - db environment: WEBPACKER_DEV_SERVER_HOST: webpacker MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} RAILS_MASTER_KEY: ${RAILS_MASTER_KEY} SENDGRID_API_KEY: ${SENDGRID_API_KEY} ADMIN_USER_PASSWORD: ${ADMIN_USER_PASSWORD} AWS_ACCESS_KEY_ID: ${AWS_ACCESS_KEY_ID} AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY} GOOGLE_USER_NAME: ${GOOGLE_USER_NAME} GOOGLE_PASSWORD: ${GOOGLE_PASSWORD} SENDGRID_USER_NAME: ${SENDGRID_USER_NAME} SENDGRID_PASSWORD: ${SENDGRID_PASSWORD} PAYJP_SECRET_KEY: ${PAYJP_SECRET_KEY} PAYJP_PUBLIC_KEY: ${PAYJP_PUBLIC_KEY} MYSQL_HOST: db # selenium_chrome を使うために以下の行を追加 SELENIUM_DRIVER_URL: http://selenium_chrome:4444/wd/hub" selenium_chrome: image: selenium/standalone-chrome-debug logging: driver: none webpacker: <<: *web command: ./bin/webpack-dev-server environment: WEBPACKER_DEV_SERVER_HOST: 0.0.0.0 ports: - "3035:3035" volumes: mysql-data: driver: local vendor_bundle: driver: local
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Dockerでyarnの依存関係を解決。

docker-compose upで RUN yarn upgrade の部分でエラーがでた。 Step 13/19 : RUN yarn upgrade ---> Running in 3c8f3922483b yarn upgrade v1.22.17 warning package-lock.json found. Your project contains lock files generated by tools other than Yarn. It is advised not to mix package managers in order to avoid resolution inconsistencies caused by unsynchronized lock files. To clear this warning, remove package-lock.json. [1/4] Resolving packages... info There appears to be trouble with your network connection. Retrying... warning @rails/webpacker > webpack > watchpack > watchpack-chokidar2 > chokidar@2.1.8: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies. warning @rails/webpacker > webpack > watchpack > watchpack-chokidar2 > chokidar > fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2. warning @rails/webpacker > postcss-preset-env > postcss-color-functional-notation > postcss-values-parser > flatten@1.0.3: flatten is deprecated in favor of utility frameworks such as lodash. warning @rails/webpacker > webpack > node-libs-browser > url > querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead. warning @rails/webpacker > optimize-css-assets-webpack-plugin > cssnano > cssnano-preset-default > postcss-svgo > svgo@1.3.2: This SVGO version is no longer supported. Upgrade to v2.x.x. warning @rails/webpacker > webpack > micromatch > snapdragon > source-map-resolve > resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated warning @rails/webpacker > webpack > micromatch > snapdragon > source-map-resolve > urix@0.1.0: Please see https://github.com/lydell/urix#deprecated [2/4] Fetching packages... error @npmcli/fs@1.1.0: The engine "node" is incompatible with this module. Expected version "^12.13.0 || ^14.15.0 || >=16". Got "10.24.0" error Found incompatible module. info Visit https://yarnpkg.com/en/docs/cli/upgrade for documentation about this command. The command '/bin/sh -c yarn upgrade' returned a non-zero code: 1 ERROR: Service 'web' failed to build : Build failed warning package-lock.json found. Your project contains lock files generated by tools other than Yarn. It is advised not to mix package managers in order to avoid resolution inconsistencies caused by unsynchronized lock files. To clear this warning, remove package-lock.json. It is advised not to mix package managers in order to avoid resolution inconsistencies caused by unsynchronized lock files. そのとおりでしかないので、package-lock.jsonを消した。npmとyarnを混在させてた。packge.jsonをどっちも使うから互換性あると思ってたが、lockファイルはまた別の話か。 The engine “node” is incompatible with this module が核となる部分か。 error @npmcli/fs@1.1.0: The engine "node" is incompatible with this module. Expected version "^12.13.0 || ^14.15.0 || >=16". Got "10.24.0" nodeのバージョンが古いと怒られてる気がする node -v v16.13.1 ローカルではこうだったが、docker上では Got "10.24.0"となってるので 16系のnodeをインストールするDockerfileを記述したい。 Dockerfileにこのように記述してみた。 RUN curl -sL https://deb.nodesource.com/setup_16.x | bash - && \ #←ここ変更 apt-get install -y nodejs  docker-compose upを実行。 ├─ wrap-ansi@5.1.0 ├─ ws@8.4.0 ├─ xtend@4.0.2 ├─ yaml@1.10.2 ├─ yargs-parser@13.1.2 ├─ yargs@13.3.2 ├─ yocto-queue@0.1.0 └─ youtube-player@5.5.2 Done in 116.92s. RUN yarn upgrade を突破した!!!やったぜ!! s:46 webpacker_1 | return func(...args); webpacker_1 | ^ webpacker_1 | webpacker_1 | TypeError: Class constructor ServeCommand cannot be invoked without 'new' webpacker_1 | at runWhenInstalled (/coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:46:9) webpacker_1 | at promptForInstallation (/coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:140:10) webpacker_1 | at /coffee_passport/node_modules/webpack-cli/bin/cli.js:32:43 webpacker_1 | at Object.<anonymous> (/coffee_passport/node_modules/webpack-cli/bin/cli.js:366:3) webpacker_1 | at Module._compile (node:internal/modules/cjs/loader:1101:14) webpacker_1 | at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) webpacker_1 | at Module.load (node:internal/modules/cjs/loader:981:32) webpacker_1 | at Function.Module._load (node:internal/modules/cjs/loader:822:12) webpacker_1 | at Module.require (node:internal/modules/cjs/loader:1005:19) webpacker_1 | at require (node:internal/modules/cjs/helpers:102:18) coffee_passport_webpacker_1 exited with code 1 しかしwebpackerコンテナはこのようになってた。。 依存関係がやばいからだとおもうので、過去の自分の記事を参考に https://qiita.com/divclass123/items/5cee396071540256e11e Dockerfileに RUN yarn upgrade-interactive --latest これをついか。 この記事のように、このコマンドは対話型で、依存関係を直していくので、 RUN yarn upgrade-interactive --latest このコマンド書くだけでは不十分なのではないか。 実際自分がローカルで、yarn upgrade-interactive --latestを叩いたときには 対話型の画面になって、aを押した後にエンターを押した。 RUN a RUN enter とドッカーファイルに書くことができればいいのだが。。。 もしくは、COPY . /coffee_passport でキャッシュが使われてる気がするので、 ローカルで依存を直しても、依存を直す以前のディレクトリがコピーされていたら全く意味がないので docker-compose build --no-cache を実行する必要があるのではないか。 Step 15/21 : RUN yarn upgrade-interactive --latest ---> Running in 5330c7208d1b yarn upgrade-interactive v1.22.17 success All of your dependencies are up to date. Done in 6.03s. とdocker-composeのログをみたらなっていた。 つまり RUN yarn upgrade-interactive --latest 単体でも機能していた。 これで依存関係が治ればいいのだが、、。。。 Recreating coffee_passport_webpacker_1 ... error ERROR: for coffee_passport_webpacker_1 cannot stop container: d0dea180963dc92a187a59c4a4Recreating coffee_passport_web_1 ... error xit event ERROR: for coffee_passport_web_1 cannot stop container: a07b86322e13b4796550a99f01af6c0fd4a2279a3f05e5b210eb06cd0a171c57: tried to kill container, but did not receive an exit event ERROR: for webpacker cannot stop container: d0dea180963dc92a187a59c4a462dfebc52a85d5071cfec4ef746f162dd59009: tried to kill container, but did not receive an exit event ERROR: for web cannot stop container: a07b86322e13b4796550a99f01af6c0fd4a2279a3f05e5b210eb06cd0a171c57: tried to kill container, but did not receive an exit event ERROR: Encountered errors while bringing up the project. 依存関係とは別のエラーがでた。。。一旦dockerをまっさらにして、やり直そう。 コンテナが止まらないので、再起動。 すべてのネットワークと、ボリューム、コンテナを削除できた。 docker-compose build --no-cache を実行。 --no-cacheつける意味ない気がするが念には念を くそほど、長くロードされてる。 ---> 69212fdb637b Successfully built 69212fdb637b Successfully tagged coffee_passport_webpacker:latest Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them と一旦ビルドは成功。 docker-compose up を実行。 [24] ./app/javascript/packs/components/about_coffee_passport.vue + 2 modules 3.2 KiB {3} {11} {12} {14} [built] | 3 modules [25] ./app/javascript/packs/components/contact.vue + 2 modules 1.74 KiB {4} {11} {12} {14} [built] | 3 modules [49] ./app/javascript/packs/router/router.js 469 bytes {11} {12} {14} [built] [52] ./app/javascript/packs/components/static_pages/appExplain.vue + 4 modules 5.41 KiB {0} {9} [built] | 5 modules [53] ./app/javascript/packs/components/footer.vue + 2 modules 1.16 KiB {6} {11} [built] | 3 modules [60] ./app/javascript/packs/tag.js 5.77 KiB {1} {15} [built] [61] ./app/javascript/packs/preview.js 2.77 KiB {1} {13} [built] [64] ./app/javascript/packs/app_explain.js 329 bytes {0} [built] [65] ./app/javascript/packs/application.js 911 bytes {1} [built] [74] ./app/javascript/packs/footer.js 192 bytes {11} [built] [89] ./app/javascript/packs/hello_vue.js + 5 modules 9.73 KiB {12} [built] | ./app/javascript/packs/hello_vue.js 2.19 KiB [built] | ./app/javascript/app.vue 552 bytes [built] | ./app/javascript/app.vue?vue&type=template&id=286cd28a&scoped=true& 213 bytes [built] | ./app/javascript/app.vue?vue&type=script&lang=js& 364 bytes [built] | ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./app/javascript/app.vue?vue&type=template&id=286cd28a&scoped=true& 3.95 KiB [built] | ./node_modules/babel-loader/lib??ref--7-0!./node_modules/vue-loader/lib??vue-loader-options!./app/javascript/app.vue?vue&type=script&lang=js& 2.44 KiB [built] [90] ./app/javascript/packs/components/Home.vue + 2 modules 826 bytes {2} [built] | 3 modules + 76 hidden modules こんな感じでコンパイルも成功してそう。 だし、docekr-compose up成功してくれ、、、 webpacker_1 | /coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:46 webpacker_1 | return func(...args); webpacker_1 | ^ webpacker_1 | webpacker_1 | TypeError: Class constructor ServeCommand cannot be invoked without 'new' webpacker_1 | at runWhenInstalled (/coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:46:9) webpacker_1 | at promptForInstallation (/coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:140:10) webpacker_1 | at /coffee_passport/node_modules/webpack-cli/bin/cli.js:32:43 webpacker_1 | at Object. (/coffee_passport/node_modules/webpack-cli/bin/cli.js:366:3) webpacker_1 | at Module._compile (node:internal/modules/cjs/loader:1101:14) webpacker_1 | at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) webpacker_1 | at Module.load (node:internal/modules/cjs/loader:981:32) webpacker_1 | at Function.Module._load (node:internal/modules/cjs/loader:822:12) webpacker_1 | at Module.require (node:internal/modules/cjs/loader:1005:19) webpacker_1 | at require (node:internal/modules/cjs/helpers:102:18) coffee_passport_webpacker_1 exited with code 1 だめだぁ。。。・・・・ reating coffee_passport_db_1 ... done Creating coffee_passport_selenium_chrome_1 ... done Creating coffee_passport_webpacker_1 ... done Creating coffee_passport_web_1 ... done Attaching to coffee_passport_db_1, coffee_passport_webpacker_1, coffee_passport_web_1 db_1 | 2021-12-23 15:14:49+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.21-1debian10 started. db_1 | 2021-12-23 15:14:49+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql' db_1 | 2021-12-23 15:14:49+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.21-1debian10 started. db_1 | 2021-12-23 15:14:49+00:00 [Note] [Entrypoint]: Initializing database files db_1 | 2021-12-23T15:14:49.935688Z 0 [System] [MY-013169] [Server] /usr/sbin/mysqld (mysqld 8.0.21) initializing of server in progress as process 44 db_1 | 2021-12-23T15:14:49.944995Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started. db_1 | 2021-12-23T15:14:50.495413Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended. db_1 | 2021-12-23T15:14:52.240716Z 6 [Warning] [MY-010453] [Server] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option. webpacker_1 | /coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:46 webpacker_1 | return func(...args); webpacker_1 | ^ webpacker_1 | webpacker_1 | TypeError: Class constructor ServeCommand cannot be invoked without 'new' webpacker_1 | at runWhenInstalled (/coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:46:9) webpacker_1 | at promptForInstallation (/coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:140:10) webpacker_1 | at /coffee_passport/node_modules/webpack-cli/bin/cli.js:32:43 webpacker_1 | at Object.<anonymous> (/coffee_passport/node_modules/webpack-cli/bin/cli.js:366:3) webpacker_1 | at Module._compile (node:internal/modules/cjs/loader:1101:14) webpacker_1 | at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) webpacker_1 | at Module.load (node:internal/modules/cjs/loader:981:32) webpacker_1 | at Function.Module._load (node:internal/modules/cjs/loader:822:12) webpacker_1 | at Module.require (node:internal/modules/cjs/loader:1005:19) webpacker_1 | at require (node:internal/modules/cjs/helpers:102:18) coffee_passport_webpacker_1 exited with code 1 db_1 | 2021-12-23 15:14:55+00:00 [Note] [Entrypoint]: Database files initialized db_1 | 2021-12-23 15:14:55+00:00 [Note] [Entrypoint]: Starting temporary server db_1 | 2021-12-23T15:14:55.874976Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.21) starting as process 91 db_1 | 2021-12-23T15:14:55.894098Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started. db_1 | 2021-12-23T15:14:56.143204Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended. db_1 | 2021-12-23T15:14:56.253183Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: /var/run/mysqld/mysqlx.sock db_1 | 2021-12-23T15:14:56.401692Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed. db_1 | 2021-12-23T15:14:56.402164Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel. db_1 | 2021-12-23T15:14:56.407071Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory. db_1 | 2021-12-23T15:14:56.434607Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.21' socket: '/var/run/mysqld/mysqld.sock' port: 0 MySQL Community Server - GPL. db_1 | 2021-12-23 15:14:56+00:00 [Note] [Entrypoint]: Temporary server started. db_1 | Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it. db_1 | Warning: Unable to load '/usr/share/zoneinfo/leap-seconds.list' as time zone. Skipping it. db_1 | Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it. db_1 | Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it. db_1 | db_1 | 2021-12-23 15:14:59+00:00 [Note] [Entrypoint]: Stopping temporary server db_1 | 2021-12-23T15:14:59.658326Z 10 [System] [MY-013172] [Server] Received SHUTDOWN from user root. Shutting down mysqld (Version: 8.0.21). db_1 | 2021-12-23T15:15:01.954163Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.21) MySQL Community Server - GPL. db_1 | 2021-12-23 15:15:02+00:00 [Note] [Entrypoint]: Temporary server stopped db_1 | db_1 | 2021-12-23 15:15:02+00:00 [Note] [Entrypoint]: MySQL init process done. Ready for start up. db_1 | db_1 | 2021-12-23T15:15:02.932785Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.21) starting as process 1 db_1 | 2021-12-23T15:15:02.943118Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started. db_1 | 2021-12-23T15:15:03.122522Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended. db_1 | 2021-12-23T15:15:03.216008Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock db_1 | 2021-12-23T15:15:03.332617Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed. db_1 | 2021-12-23T15:15:03.332862Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel. db_1 | 2021-12-23T15:15:03.336670Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory. db_1 | 2021-12-23T15:15:03.357237Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.21' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server - GPL. しかもwebコンテナがdoneになってるのにログに表示されないし localhost:3000も受け付けてくれない。 このページは動作してませんとなる・ soichirohara@SoichironoMacBook-Pro coffee_passport % docker-compose ps Name Command State Ports coffee_passport_db_1 docker-entrypoint.sh --def Up 0.0.0.0:3306->3306/tcp, ... 33060/tcp coffee_passport_selenium_ch /opt/bin/entry_point.sh Up 4444/tcp, 5900/tcp rome_1 coffee_passport_web_1 entrypoint.sh ./bin/rails Up 0.0.0.0:3000->3000/tcp ... coffee_passport_webpacker_1 entrypoint.sh ./bin/webpac Exit 1 ... coffee_passport_web_1 コンテナ立ち上がってるはずなのに。。。 coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:46 return func(...args); ^ TypeError: Class constructor ServeCommand cannot be invoked without 'new' at runWhenInstalled (/coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:46:9) at promptForInstallation (/coffee_passport/node_modules/webpack-cli/bin/utils/prompt-command.js:140:10) at /coffee_passport/node_modules/webpack-cli/bin/cli.js:32:43 at Object.<anonymous> (/coffee_passport/node_modules/webpack-cli/bin/cli.js:366:3) at Module._compile (node:internal/modules/cjs/loader:1101:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Module.require (node:internal/modules/cjs/loader:1005:19) at require (node:internal/modules/cjs/helpers:102:18) webpackerコンテナ全体のログはこんな感じ TypeError: Class constructor ServeCommand cannot be invoked without 'new' をググったら。 これは今のところうまくいきました。package.jsonファイルのwebpack-dev-serverバージョンを次のように変更します。 "webpack-dev-server": "~3" そして、yarn installまたはを実行しnpm installます。 ソース:https://stackoverflow.com/a/69050300/2774342 PSこれは一時的な解決策になる可能性がありますが、新しいバージョンがリリースされるため、将来の参照(数か月後だと思います)のために、この回答は非推奨になります。 とかいてあったので webpack-dev-serverをバージョン3のままにする これを行うには、package.jsonファイルを更新します。 package.json "webpack-dev-server": "~3" をこうする。 - RUN bundle exec rails webpacker:compile - RUN yarn upgrade-interactive --latest をけした。コンパイル専用のコンテナがあるので、わざわざDockerfileに記述しなくてもいいとおもった。 RUN yarn upgrade-interactive --latest は "webpack-dev-server": "~3"とバージョンを固定したいので、 アップデートをしてしまうコマンドを削除 RUN yarn install --check-files を追記 docker-compose up で成功!! やったぜ!! 上手く言ったdockerfileとdocker-compose.yml FROM ruby:2.6.5 ## nodejsとyarnはwebpackをインストールする際に必要 # yarnパッケージ管理ツールをインストール RUN curl http://deb.debian.org/debian/dists/buster/main/binary-amd64/by-hash/SHA256/935deda18d5bdc25fb1813d0ec99b6e0e32a084b203e518af0cf7dc79ee8ebda | head RUN apt-get update && apt-get install -y curl apt-transport-https wget && \ 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 && apt-get install -y yarn && apt-get install -y graphviz RUN curl -sL https://deb.nodesource.com/setup_16.x | bash - && \ apt-get install -y nodejs # chromeの追加 RUN apt-get update && apt-get install -y unzip && \ CHROME_DRIVER_VERSION=`curl -sS chromedriver.storage.googleapis.com/LATEST_RELEASE` && \ wget -N http://chromedriver.storage.googleapis.com/$CHROME_DRIVER_VERSION/chromedriver_linux64.zip -P ~/ && \ unzip ~/chromedriver_linux64.zip -d ~/ && \ rm ~/chromedriver_linux64.zip && \ chown root:root ~/chromedriver && \ chmod 755 ~/chromedriver && \ mv ~/chromedriver /usr/bin/chromedriver && \ sh -c 'wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -' && \ sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list' && \ apt-get update && apt-get install -y google-chrome-stable RUN /bin/sh -c /bin/sh -c bundle update --bundler RUN gem install bundler:2.1.4 RUN mkdir /coffee_passport WORKDIR /coffee_passport COPY . /coffee_passport COPY Gemfile /coffee_passport/Gemfile COPY Gemfile.lock /coffee_passport/Gemfile.lock # RUN bundle update rails # RUN bundle update # RUN bundle update mimemagic # RUN bundle update capybara selenium-webdriver #RUN bundle update nokogiri marcel mimemagic RUN bundle install RUN yarn upgrade #RUN yarn upgrade-interactive --latest #RUN bundle exec rails webpacker:comp RUN yarn install --check-files # 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"] docker-compose.yml version: '3' services: db: image: mysql:8.0.21 cap_add: - SYS_NICE # コンテナにLinux機能を追加するオプションのようです。SYS_NICEは、プロセスの優先度(nice値)をあげます。 environment: MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} MYSQL_HOST: db ports: - '3306:3306' volumes: - mysql-data:/var/lib/mysql command: --default-authentication-plugin=mysql_native_password # 認証方式を8系以前のものにする web: &web build: . command: ./bin/rails s -b 0 stdin_open: true tty: true # この2文を追加でコンテナ内の標準入出力をローカルマシンのターミナルにアタッチする準備が整います。 volumes: - .:/coffee_passport ports: - "3000:3000" depends_on: - db environment: WEBPACKER_DEV_SERVER_HOST: webpacker MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} RAILS_MASTER_KEY: ${RAILS_MASTER_KEY} SENDGRID_API_KEY: ${SENDGRID_API_KEY} ADMIN_USER_PASSWORD: ${ADMIN_USER_PASSWORD} AWS_ACCESS_KEY_ID: ${AWS_ACCESS_KEY_ID} AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY} GOOGLE_USER_NAME: ${GOOGLE_USER_NAME} GOOGLE_PASSWORD: ${GOOGLE_PASSWORD} SENDGRID_USER_NAME: ${SENDGRID_USER_NAME} SENDGRID_PASSWORD: ${SENDGRID_PASSWORD} PAYJP_SECRET_KEY: ${PAYJP_SECRET_KEY} PAYJP_PUBLIC_KEY: ${PAYJP_PUBLIC_KEY} MYSQL_HOST: db # selenium_chrome を使うために以下の行を追加 SELENIUM_DRIVER_URL: http://selenium_chrome:4444/wd/hub" selenium_chrome: image: selenium/standalone-chrome-debug logging: driver: none webpacker: <<: *web command: ./bin/webpack-dev-server environment: WEBPACKER_DEV_SERVER_HOST: 0.0.0.0 ports: - "3035:3035" volumes: mysql-data: driver: local vendor_bundle: driver: local
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

ローカル環境でMySQLが立ち上がらないときの解決策

rake aborted! ActiveRecord::ConnectionNotEstablished: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (38) というエラーが発生した。/tmpディレクトリを確認してもmysql.sockはしっかりと存在する。 mysqlを起動してみると下記のエラーが起こっていることが判明した。 $ sudo mysql.server start Password: Starting MySQL .Logging to '/usr/local/var/mysql/fujiwaratakuminoMacBook-Pro.local.err'. ERROR! The server quit without updating PID file (/usr/local/var/mysql/fujiwaratakuminoMacBook-Pro.local.pid). というエラーが起こっていることが判明した。 pidファイルとは? 「.pid」で終わっているファイルがpidファイルです。このファイルには、該当するプロセスのプロセスIDなどの情報が記述されています。たとえば、/var/run/crond.pidファイルには、crondのプロセスIDが記述されています。 このファイルは、スクリプトやほかのプロセスで利用されます。プロセスIDが記述されているので、このファイルはプロセスの制御(再起動や停止など)、プロセス同士の連携などに利用されます。 参照先 「/var/run」ディレクトリ ググった末にmysql起動時でエラーが起きた時の対処の記事を参考に $ sudo rm /tmp/mysql.sock $ chown -R _mysql:_mysql mysql を実行。再度sudo mysql.server restartを実行するが、 $ sudo mysql.server restart ERROR! MySQL server PID file could not be found! Starting MySQL .Logging to '/usr/local/var/mysql/fujiwaratakuminoMacBook-Pro.local.err'. ERROR! The server quit without updating PID file (/usr/local/var/mysql/fujiwaratakuminoMacBook-Pro.local.pid). と違うエラーが発生した。/tmp/mysql.sockを消したのがまずかったのかと思った。 今度は、mysql 起動時のThe server quit without updating PID file エラーの回避法を参考にした。 $ ls /usr/local/var/mysqlを実行してみると*****.local.pidがなかった。 $ touch /usr/local/var/mysql/*****.local.pid を実行。sudo mysql.server restartを実行してみるが、*****.local.pidに権限がなかったので、 sudo chown -R _mysql:_mysql /usr/local/var/mysql/ これで無事動くことができました! 参考にさせて頂いていたサイト 「/var/run」ディレクトリ mysql起動時でエラーが起きた時の対処 mysql 起動時のThe server quit without updating PID file エラーの回避法
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

MySQLが立ち上がらないときの解決策

rake aborted! ActiveRecord::ConnectionNotEstablished: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (38) というエラーが発生した。/tmpディレクトリを確認してもmysql.sockはしっかりと存在する。 mysqlを起動してみると下記のエラーが起こっていることが判明した。 $ sudo mysql.server start Password: Starting MySQL .Logging to '/usr/local/var/mysql/fujiwaratakuminoMacBook-Pro.local.err'. ERROR! The server quit without updating PID file (/usr/local/var/mysql/fujiwaratakuminoMacBook-Pro.local.pid). というエラーが起こっていることが判明した。 pidファイルとは? 「.pid」で終わっているファイルがpidファイルです。このファイルには、該当するプロセスのプロセスIDなどの情報が記述されています。たとえば、/var/run/crond.pidファイルには、crondのプロセスIDが記述されています。 このファイルは、スクリプトやほかのプロセスで利用されます。プロセスIDが記述されているので、このファイルはプロセスの制御(再起動や停止など)、プロセス同士の連携などに利用されます。 参照先 「/var/run」ディレクトリ ググった末にmysql起動時でエラーが起きた時の対処の記事を参考に $ sudo rm /tmp/mysql.sock $ chown -R _mysql:_mysql mysql を実行。再度sudo mysql.server restartを実行するが、 $ sudo mysql.server restart ERROR! MySQL server PID file could not be found! Starting MySQL .Logging to '/usr/local/var/mysql/fujiwaratakuminoMacBook-Pro.local.err'. ERROR! The server quit without updating PID file (/usr/local/var/mysql/fujiwaratakuminoMacBook-Pro.local.pid). と違うエラーが発生した。/tmp/mysql.sockを消したのがまずかったのかと思った。 今度は、mysql 起動時のThe server quit without updating PID file エラーの回避法を参考にした。 $ ls /usr/local/var/mysqlを実行してみると*****.local.pidがなかった。 $ touch /usr/local/var/mysql/*****.local.pid を実行。sudo mysql.server restartを実行してみるが、*****.local.pidに権限がなかったので、 sudo chown -R _mysql:_mysql /usr/local/var/mysql/ これで無事動くことができました! 参考にさせて頂いていたサイト 「/var/run」ディレクトリ mysql起動時でエラーが起きた時の対処 mysql 起動時のThe server quit without updating PID file エラーの回避法
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Railsでエラーメッセージを表示させる方法

手順 ①バリデーションの定義 ②エラーメッセージの記入 ③エラーメッセージを日本語化 ①バリデーションの定義 エラーメッセージはエラーが発生すると、error.full_message内に格納される。 バリデーションはモデル内で定義。 以下のように書くと、nameかemailを空白で登録した際は登録できないようにするバリデーションを追加することができる。 class User < ApplicationRecord validates :name, presence: true validates :email, presence: true end ②エラーメッセージの記入 エラーメッセージを記入する前に、前提として以下の3つを注意する。 ・エラーメッセージ表示部分をformのテンプレートに記載せず、専用のパーシャルが作られていること。 ・特定のモデルに依存せず汎用的なつくりにする必要がある。格納場所はshared配下にすること。 ・エラーメッセージの表示方法はアプリケーションごとに異なるため、エラーメッセージを直接生成するようなビューヘルパーはRailsに含まれてない。 表示が必要な場合はパーシャル化して、汎用的に使えるようにする。 記入例 #shared/_error_messages.html.erb <% if object.errors.any? %> <div class="alert alert-danger"> <ul class="mb-0"> <% object.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> #app/views/boards/_form.html.erb(パーシャルを呼び出し) <%= form_with model: board, local: true do |f| %> <%= render 'shared/error_messages', object: f.object %>※ <div class="form-group"> <%= f.label :title %> f.objectとは f.objectのobjectは、form_withやform_forなどのオプションであり、formのブロック変数に対して使用する事でブロック内でモデルオブジェクトを呼び出す事が出来る。 同じコードを流用する際に、変数を変える必要が無くなる。 ③エラーメッセージを日本語化 エラーメッセージを入れる前に、railsアプリを既に日本語化していた場合は特に必要なし。 ・config/application.rbにconfig.i18n.default_locale = :jaを追加。 ・gem 'rails-i18n'をインストール。 ・activerecord/ja.ymlにモデルの日本語化を記入。 例: ja: activerecord: models: user: ユーザー attributes: user: first_name: 名 last_name: 姓 email: メールアドレス password: パスワード password_confirmation: パスワード確認 これらを設定すると、「タイトルを入力してください」「本文を入力してください」のようなエラーメッセージが表示される。 参考記事 Ruby on Railsでエラーメッセージを表示する方法【初心者向け】 Rails フォーム入力時エラー情報を個別表示(f. objectについて) Rails6 エラーメッセージの日本語化
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

ActiveRecordのNullリレーションが便利そう

はじめに Railsガイドを読み返していたら便利そうなものを見つけたので備忘録代わりに残しておきます。 Nullリレーション noneメソッドは、チェーン (chain) 可能なリレーションを返します (レコードは返しません)。このメソッドから返されたリレーションにどのような条件をチェーンさせても、常に空のリレーションが生成されます。これは、メソッドまたはスコープへのチェーン可能な応答が必要で、しかも結果を一切返したくない場合に便利です。 irb(main):001:0> User.none => [] irb(main):002:0> User.none.class => User::ActiveRecord_Relation こんな感じで、空のリレーション(Nullリレーション)を返してくれる。 irb(main):003:0> User.none.limit(1) => [] リレーションを期待しているコードに対しても正常に応答するので、より保守性の高いコードが書けそう。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

chartkickのグラフが表示されない

環境 Docker mysql 8.0 rails6.1.4 ruby3.0.2 intel版Mac使用 考えられる原因 view側(html.erb)のコードの記述の問題でうまくデータを抽出できてないかとも思ったが、 <%= pie_chart [['赤', 50], ['青', 50]]%> と公式のお試しコードで記述してもグラフ出ないので、コーディングの部分ではなさそう。 chromeの検証でconsoleを調べた結果、エラーを発見。 application.js:1 Uncaught Error: Cannot find module 'chartkick/chart.js' at webpackMissingModule (application.js:1) at Module../app/javascript/packs/application.js (application.js:1) とりあえず、JSでエラーが起きてるのは間違いないみたい。 エラー文にはchartkickが見つかりません。と書いてある。 解決策 docker-compose exec web rails action:text install を打ったら解決した。 rails action:text install自体はやってたけど、Docker側にインストールしてなかったのが原因だと思われます。 このコマンドを打つと、マイグレーションファイルが作られる=DBに変更を加えることになる。 マイグレーションをいじるコマンド、つまりDBを操作する訳だから、DBをマウントしてるdocker側に必要な変更がされていなかったことになる。 だからエラーの原因になったのかなと解釈してますが、間違いあればご指摘ください。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Docker】Rails6 API + React(TypeScript)のSPA開発環境を構築する

はじめに 自分用のメモとして記録しておきます。 1. ディレクトリ構成の確認と必要ファイルの用意 以下のディレクトリ構成になるようにファイルを用意する。 $ mkdir backend $ mkdir frontend $ touch docker-compose.yml $ touch backend/Gemfile $ touch backend/Gemfile.lock $ touch backend/entrypoint.sh $ touch backend/Dockerfile $ touch frontend/Dockerfile 2. docker-compose.ymlの編集 docker-compose.yml version: "3" services: db: image: mysql:8.0 environment: MYSQL_ROOT_PASSWORD: password command: --default-authentication-plugin=mysql_native_password volumes: - mysql-data:/var/lib/mysql - /tmp/dockerdir:/etc/mysql/conf.d/ ports: - 3306:3306 api: build: context: ./backend/ dockerfile: Dockerfile command: /bin/sh -c "rm -f /myapp/tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'" image: rails:dev volumes: - ./backend:/myapp - ./backend/vendor/bundle:/myapp/vendor/bundle environment: TZ: Asia/Tokyo RAILS_ENV: development ports: - 3001:3000 depends_on: - db volumes: mysql-data: 3. API側の環境構築 3-1. 各ファイルの編集 backend/Dockerfile FROM ruby:3.0 RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs ENV APP_PATH /myapp RUN mkdir $APP_PATH WORKDIR $APP_PATH COPY Gemfile $APP_PATH/Gemfile COPY Gemfile.lock $APP_PATH/Gemfile.lock RUN bundle install COPY . $APP_PATH # 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"] backend/Gemfile source 'https://rubygems.org' gem 'rails', '>= 6.1.4.1' backend/Gemfile.lock # 空のまま backend/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 "$@" 3-2. Railsアプリケーションの作成 $ docker-compose run --no-deps api rails new . --force -d mysql --api オプションについて docker-compose run に対するオプション --no-deps: リンクしたサービス(今回であればdepends_onで指定したdb)を起動しない rails new に対するオプション --force(-f): ファイルが既に存在している場合は上書きする -d(--database): データベースの種類 --api: apiモードでアプリケーションを作成 3-3. build rails newでGemfileが更新されたのでdocker-compose buildを実行する $ docker-compose build 3-4. database.ymlの編集 backend/config/database.yml default: &default adapter: mysql2 encoding: utf8mb4 pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> username: root password: password # デフォルトだと空欄になっているので変更 host: db # デフォルトだとlocalhostになっているので変更 development: <<: *default database: myapp_development test: <<: *default database: myapp_test production: <<: *default database: <%= ENV["DATABASE_NAME"] %> username: <%= ENV["DATABASE_USERNAME"] %> password: <%= ENV["DATABASE_PASSWORD"] %> host: <%= ENV["DATABASE_HOST"] %> 3-5. データベースの作成 データベースを作成しないと以下のようにデータベースがないと怒られます。 $ docker-compose run api rails db:create ー API側の環境構築は以上になります。 4. Front側の環境構築 4-1. docker-compose.ymlにfront側の処理を追加 docker-compose.yml version: "3" services: db: ... api: ... # ↓ 追加 front: build: context: ./frontend/ dockerfile: Dockerfile volumes: - ./frontend:/usr/src/app command: sh -c "cd app && yarn && yarn start" ports: - "4000:3000" volumes: mysql-data: 4-2. Dockerfileの編集 frontend/Dockerfile FROM node:14.18-alpine WORKDIR /usr/src/app 4-3. build $ docker-compose build 4-4. アプリケーション作成 アプリケーション名はappとする。 TypeScriptを使いたので最後に--template typescript を追加する。 nodeのバージョンによってはESlint等をインストールする際にエラーが発生する可能性があるので、適宜、nodeイメージのバージョンを変更する。 参考: https://hub.docker.com/_/node npmで管理する場合 $ docker-compose run --rm front sh -c "npx create-react-app app --template typescript" yarnで管理する場合(<= 今回はこちら) $ docker-compose run --rm front sh -c "yarn create react-app app --template typescript" ※ yarnはnodeのイメージ(node:14.18-alpine)にデフォルトで入っているらしいのでインストールは不要。 参考: https://github.com/nodejs/docker-node/blob/b695e030ea98f272d843feb98ee1ab62943071b3/14/alpine3.14/Dockerfile 4-5. ディレクトリ構成の確認 以下のように指定したappディレクトリ配下にnode_modules, public, srcディレクトリ、pacage.json、tsconfig.json, yarn.lockファイル等が作成されていることが確認できます。 5. 各コンテナを立ち上げる $ docker-compose up -d 6. 確認 API側 http://localhost:3001 にアクセス Front側 http://localhost:4000 にアクセス ー 無事に初期画面が表示されました。 参考
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む