この記事の英語版に更新があります。ご覧の翻訳には含まれていない変更点があるかもしれません。
最終更新日 2024年11月13日(水)
Ruby on Rails は、Ruby で記述され、広く使われている Web フレームワークです。このガイドでは、Heroku での Rails 8 の使用について説明します。Heroku での Rails 旧バージョンの実行についての詳細は、Rails 7.x または Rails 6.x に関するチュートリアルを参照してください。
このチュートリアルでは、以下が用意されていることを前提としています。
- Ruby、Ruby on Rails、および Git に関する基本的な知識
- Ruby 3.2.0+、Rubygems、Bundler、Rails 8 のローカルにインストールされたバージョン+
- Heroku CLI のローカルにインストールされたバージョン
- 確認済みの Heroku アカウント
- Eco dyno プランのサブスクリプション (推奨)
dyno とデータベースを使用してこのチュートリアルを完了した場合、使用量のカウントに入ります。低料金プランを使用してこのチュートリアルを完了することをお勧めします。資格のある学生の皆様は、新しい Heroku for GitHub Students プログラムを通じてプラットフォームクレジットを申請できます。
ローカルの設定
Heroku CLI のインストール後、ターミナルからログインします。
$ heroku login heroku: Press any key to open up the browser to login or q to exit › Warning: If browser does not open, visit › https://cli-auth.heroku.com/auth/browser/*** heroku: Waiting for login... Logging in... done Logged in as developer@example.com このコマンドにより、Web ブラウザで Heroku ログインページが開きます。ブラウザですでに Heroku にログインしている場合は、ページの Log in (ログイン) ボタンをクリックします。
この認証は、heroku と git コマンドが正常に動作するために必要な操作です。
外部の HTTP/HTTPS サービスへの接続にプロキシを使用するファイアウォールを利用している場合は、heroku コマンドを実行する前に、ローカルの開発環境で HTTP_PROXY または HTTPS_PROXY 環境変数を設定してください。
新しい Rails アプリの作成または既存の Rails アプリのアップグレード
アプリを作成する前に、rails -v を実行して、Rails 8 がインストールされていることを確認します。必要に応じて、gem install を使用して Rails 8 をインストールします。
$ gem install rails --no-document Successfully installed zeitwerk-2.7.1 Successfully installed rack-3.1.8 Successfully installed rackup-2.2.0 Successfully installed reline-0.5.11 Successfully installed irb-1.14.1 Successfully installed uri-1.0.1 Successfully installed concurrent-ruby-1.3.4 Successfully installed tzinfo-2.0.6 Successfully installed securerandom-0.3.2 PSA: I18n will be dropping support for Ruby < 3.2 in the next major release (April 2025), due to Ruby's end of life for 3.1 and below (https://endoflife.date/ruby). Please upgrade to Ruby 3.2 or newer by April 2025 to continue using future versions of this gem. Successfully installed i18n-1.14.6 Successfully installed connection_pool-2.4.1 Successfully installed benchmark-0.4.0 Successfully installed activesupport-8.0.0 Successfully installed useragent-0.16.10 Successfully installed crass-1.0.6 Successfully installed loofah-2.23.1 Successfully installed rails-html-sanitizer-1.6.0 Successfully installed rails-dom-testing-2.2.0 Successfully installed rack-session-2.0.0 Successfully installed erubi-1.13.0 Successfully installed builder-3.3.0 Successfully installed actionview-8.0.0 Successfully installed actionpack-8.0.0 Successfully installed railties-8.0.0 Successfully installed marcel-1.0.4 Successfully installed timeout-0.4.2 Successfully installed activemodel-8.0.0 Successfully installed activerecord-8.0.0 Successfully installed globalid-1.2.1 Successfully installed activejob-8.0.0 Successfully installed activestorage-8.0.0 Successfully installed actiontext-8.0.0 Successfully installed mail-2.8.1 Successfully installed actionmailer-8.0.0 Successfully installed actionmailbox-8.0.0 Successfully installed websocket-extensions-0.1.5 Building native extensions. This could take a while... Successfully installed websocket-driver-0.7.6 Building native extensions. This could take a while... Successfully installed nio4r-2.7.4 Successfully installed actioncable-8.0.0 Successfully installed rails-8.0.0 40 gems installed Rails アプリを作成します。
$ rails new myapp --database=postgresql アプリケーションのディレクトリに移動します
$ cd myapp $ ls -1 Dockerfile Gemfile Gemfile.lock README.md Rakefile app bin config config.ru db lib log public script storage test tmp vendor ローカルデータベースを作成します。
$ bin/rails db:create Database 'myapp_development' already exists Database 'myapp_test' already exists pg gem の追加
--database=postgresql が定義されていない新規または既存のアプリの場合は、Gemfile 内に sqlite3 gem が存在しないことを確認します。pggem を所定の位置に追加します。
Gemfile 内で、次の行を削除します。
gem 'sqlite3' これを次の行に置き換えます。
gem 'pg' 開発中は PostgreSQL をローカルで使用することを強くお勧めします。開発環境とデプロイ環境の間の同等性を維持することにより、環境の違いによる微妙なバグが取り込まれることを防ぎます。
Postgres をローカルにインストールします。Sqlite3 の代わりに Postgres が推奨される理由についての詳細は、Sqlite3 が Heroku と互換性がない理由を参照してください。
Gemfile が更新されたら、依存関係を再インストールします。
$ bundle install インストールによって、Gemfile.lock も変更を含めて更新されます。
pg gem に加えて、config/database.yml で postgresql アダプタが定義されていることを確認します。config/database.ymlファイルの開発セクションは次のようになります。
$ cat 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 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 } %> development: <<: *default database: myapp_development # The specified database role being used to connect to PostgreSQL. # To create additional roles in PostgreSQL see `$ createuser --help`. # When left blank, PostgreSQL will use the default role. This is # the same name as the operating system user running Rails. #username: myapp # The password associated with the PostgreSQL role (username). #password: # Connect on a TCP socket. Omitted by default since the client uses a # domain socket that doesn't need configuration. Windows does not have # domain sockets, so uncomment these lines. #host: localhost # The TCP port the server listens on. Defaults to 5432. # If your server runs on a different port number, change accordingly. #port: 5432 # Schema search path. The server defaults to $user,public #schema_search_path: myapp,sharedapp,public # Minimum log levels, in increasing order: # debug5, debug4, debug3, debug2, debug1, # log, notice, warning, error, fatal, and panic # Defaults to warning. #min_messages: notice # Warning: The database defined as "test" will be erased and # re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: <<: *default database: myapp_test # As with config/credentials.yml, you never want to store sensitive information, # like your database password, in your source code. If your source code is # ever seen by anyone, they now have access to your database. # # Instead, provide the password or a full connection URL as an environment # variable when you boot the app. For example: # # DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" # # If the connection URL is provided in the special DATABASE_URL environment # variable, Rails will automatically merge its configuration values on top of # the values provided in this file. Alternatively, you can specify a connection # URL environment variable explicitly: # # production: # url: <%= ENV["MY_APP_DATABASE_URL"] %> # # Read https://guides.rubyonrails.org/configuring.html#configuring-a-database # for a full overview on how database connection configuration can be specified. # production: primary: &primary_production <<: *default database: myapp_production username: myapp password: <%= ENV["MYAPP_DATABASE_PASSWORD"] %> cache: <<: *primary_production database: myapp_production_cache migrations_paths: db/cache_migrate queue: <<: *primary_production database: myapp_production_queue migrations_paths: db/queue_migrate cable: <<: *primary_production database: myapp_production_cable migrations_paths: db/cable_migrate ここで注意点があります。adapterの値が postgres で、postgresql でない場合、アプリケーションは機能しません。
ウェルカムページの作成
Rails 8 の本番環境には、デフォルトで静的なインデックスページがありません。Rails 8 にアップグレードされたアプリでは既存のページ設定が保持されますが、新しい Rails 8 アプリでは、自動的にウェルカムページが生成されません。ホームページを保持するための welcome コントローラーを作成します。
$ rails generate controller welcome app/views/welcome/index.html.erb を作成し、次のコードを追加します。
<h2>Hello World</h2> <p> The time is now: <%= Time.now %> </p> ウェルカムページが作成されたら、このアクションにマッピングするためのルートを作成します。
ファイル config/routes.rb の 2 行目に以下を追加します。
root 'welcome#index' Rails Web サーバーを起動して、ページが表示されることを確認します。
$ rails server ブラウザで http://localhost:3000 にアクセスします。ページが表示されない場合は、ログを参照して、エラーをデバッグします。Rails によって、rails server を起動したのと同じターミナルにログが出力されます。
Ruby バージョンの指定
Rails 8 では、Ruby 3.2.0 以上が必要です。Heroku は、デフォルトでは最新バージョンの Ruby をインストールします。Gemfileで ruby DSL を使用して、特定のバージョンを指定します。たとえば、次のようになります。
ruby "3.2.6" Gemfile.lock の RUBY VERSION を、以下を実行して更新します。
$ bundle update --ruby Fetching gem metadata from https://rubygems.org/......... Resolving dependencies... Bundle updated! 変更を確認します。
$ cat Gemfile.lock | grep RUBY -a1 RUBY VERSION ruby 3.2.6p234 常にローカルでも同じバージョンの Ruby を使用します。ruby -vを使用して ruby のローカルバージョンを確認します。特定の Ruby バージョンの定義についての詳細は、「Ruby のバージョン」の記事を参照してください。
Procfile の作成
Procfile は、アプリケーションのルートディレクトリにあるテキストファイルです。このファイルを使って、アプリの起動時に実行するコマンドを明示的に宣言します。
この Procfile では、単一のプロセスタイプの web と、その実行に必要なコマンドを宣言しています。ここでは、web という名前が重要です。これは、このプロセスタイプを Heroku の HTTP ルーティングスタックにアタッチし、デプロイ後に Web トラフィックを受信することを宣言しています。
デフォルトでは、Rails アプリの Web プロセスは、Rails 8 で Puma を使用する rails server を実行します。Procfileを使用せずに Rails 8 アプリケーションをデプロイすると、このコマンドが実行されます。ただし、Procfile を介してサーバープロセスを起動する方法を明示的に宣言することをお勧めします。たとえば、次のようになります。
web: bundle exec puma -C config/puma.rb Procfile ファイル名は大文字と小文字が区別されます。ファイル拡張子はありません。
config/puma.rb が存在しない場合は、最大のパフォーマンスを得るために、Heroku の Puma ドキュメントを使用して作成してください。
Procfile には追加のプロセスタイプを含めることができます。たとえば、キューからアイテムを取り出して処理するバックグラウンドワーカープロセスを宣言できます。
Git でのアプリの保存
Heroku では、アプリケーションのデプロイを分散型ソース管理ツールである Git に依存しています。アプリケーションがまだ Git に存在しない場合は、まず git --help を使用して git がシステムに存在することを確認してください。
$ git --help usage: git [-v | --version] [-h | --help] [-C <path>] [-c <name>=<value>] [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path] [-p | --paginate | -P | --no-pager] [--no-replace-objects] [--no-lazy-fetch] [--no-optional-locks] [--no-advice] [--bare] [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>] [--config-env=<name>=<envvar>] コマンドで出力が生成されないか、または command not found の場合、Git をインストールします。
Rails アプリのルートディレクトリに移動します。lsコマンドを使用して、その内容を確認します。
$ ls Dockerfile Gemfile Gemfile-e Gemfile.lock Procfile README.md Rakefile app bin config config.ru db lib log public script storage test tmp vendor Rails アプリ内で直接、ローカルの空の Git リポジトリを初期化し、そのアプリのコードをコミットします。
$ git init $ git add . $ git commit -m "init" git status を使用して、すべてが正しくコミットされたことを確認します。
$ git status On branch main nothing to commit, working tree clean アプリケーションが Git にコミットされたら、Heroku にデプロイする準備ができています。
Heroku アプリの作成
Heroku でアプリを作成するには、Rails アプリのルートディレクトリ内で Heroku CLI を使用します。
$ heroku apps:create Creating app... done, sleepy-lake-73349 https://sleepy-lake-73349-75b72c5796f5.herokuapp.com/ | https://git.heroku.com/sleepy-lake-73349.git アプリを作成すると、heroku という名前の Git リモートリポジトリも作成され、ローカルの Git リポジトリと関連付けられます。Git リモートは、他のサーバー上で稼働するリポジトリのバージョンです。アプリに関連付けられた、Heroku でホストされる特別なリモートにコードをプッシュすることにより、アプリをデプロイします。git config でリモートが 設定されていることを確認します。
$ git config --list --local | grep heroku remote.heroku.url=https://git.heroku.com/sleepy-lake-73349.git remote.heroku.fetch=+refs/heads/*:refs/remotes/heroku/* 現在のディレクトリが正しくないか、または Git が初期化されていない場合、Git は fatal: not in a git directory を返します。Git がリモートの一覧を返した場合は、デプロイする準備ができています。
業界での変更に従い、Heroku ではデフォルトのブランチ名を main に更新しました。プロジェクトでデフォルトのブランチ名として master を使用している場合は、git push heroku master を使用してください。
データベースのプロビジョニング
Elements Marketplace から入手可能なアドオンの 1 つである Heroku Postgres データベースをプロビジョニングします。アドオンは、ログ記録、モニタリング、データベースなど、アプリケーションですぐに使える追加サービスを提供するクラウドサービスです。
mini Postgres のサイズのコストは月額 5 ドルで、分単位で課金されます。このチュートリアルの最後で、データベースを削除して、コストを最小限に抑えるように求められます。
$ heroku addons:create heroku-postgresql:essential-0 Creating heroku-postgresql:essential-0 on sleepy-lake-73349... ~$0.007/hour (max $5/month) Database should be available soon postgresql-clear-11142 is being created in the background. The app will restart when complete... Use heroku addons:info postgresql-clear-11142 to check creation progress Use heroku addons:docs heroku-postgresql to view documentation Heroku アプリでこの Postgres データベースにアクセスできるようになりました。DATABASE_URL環境変数は、規約によって Rails が接続する資格情報を格納します。
Heroku へのアプリのデプロイ
dyno を使用してこのチュートリアルを完了した場合、使用量のカウントに入ります。コストを抑制するために、完了したらすぐにアプリを削除してください。
コードをデプロイします。このコマンドは、サンプルリポジトリの main ブランチを heroku リモートにプッシュし、次に Heroku にデプロイします。
$ git push heroku main remote: Updated 109 paths from 71a5ba5 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-24 stack remote: -----> Determining which buildpack to use for this app remote: -----> Ruby app detected remote: -----> Installing bundler 2.5.6 remote: -----> Removing BUNDLED WITH version in the Gemfile.lock remote: -----> Compiling Ruby/Rails remote: -----> Using Ruby version: ruby-3.2.6 remote: -----> Installing dependencies using bundler 2.5.6 remote: Running: BUNDLE_WITHOUT='development:test' BUNDLE_PATH=vendor/bundle BUNDLE_BIN=vendor/bundle/bin BUNDLE_DEPLOYMENT=1 bundle install -j4 remote: Fetching gem metadata from https://rubygems.org/......... remote: Fetching rake 13.2.1 remote: Installing rake 13.2.1 remote: Fetching base64 0.2.0 remote: Fetching bigdecimal 3.1.8 remote: Fetching concurrent-ruby 1.3.4 remote: Fetching benchmark 0.4.0 remote: Installing benchmark 0.4.0 remote: Installing base64 0.2.0 remote: Fetching connection_pool 2.4.1 remote: Fetching drb 2.2.1 remote: Installing bigdecimal 3.1.8 with native extensions remote: Installing connection_pool 2.4.1 remote: Installing drb 2.2.1 remote: Fetching logger 1.6.1 remote: Installing logger 1.6.1 remote: Installing concurrent-ruby 1.3.4 remote: Fetching minitest 5.25.1 remote: Fetching securerandom 0.3.2 remote: Installing securerandom 0.3.2 remote: Installing minitest 5.25.1 remote: Fetching uri 1.0.1 remote: Installing uri 1.0.1 remote: Fetching builder 3.3.0 remote: Installing builder 3.3.0 remote: Fetching erubi 1.13.0 remote: Installing erubi 1.13.0 remote: Fetching racc 1.8.1 remote: Fetching crass 1.0.6 remote: Installing racc 1.8.1 with native extensions remote: Installing crass 1.0.6 remote: Fetching rack 3.1.8 remote: Fetching useragent 0.16.10 remote: Installing useragent 0.16.10 remote: Installing rack 3.1.8 remote: Fetching nio4r 2.7.4 remote: Installing nio4r 2.7.4 with native extensions remote: Fetching websocket-extensions 0.1.5 remote: Installing websocket-extensions 0.1.5 remote: Fetching zeitwerk 2.7.1 remote: Installing zeitwerk 2.7.1 remote: Fetching timeout 0.4.2 remote: Installing timeout 0.4.2 remote: Fetching marcel 1.0.4 remote: Installing marcel 1.0.4 remote: Fetching mini_mime 1.1.5 remote: Installing mini_mime 1.1.5 remote: Fetching date 3.4.0 remote: Installing date 3.4.0 with native extensions remote: Fetching bcrypt_pbkdf 1.1.1 remote: Installing bcrypt_pbkdf 1.1.1 with native extensions remote: Fetching msgpack 1.7.5 remote: Installing msgpack 1.7.5 with native extensions remote: Fetching dotenv 3.1.4 remote: Installing dotenv 3.1.4 remote: Fetching ed25519 1.3.0 remote: Installing ed25519 1.3.0 with native extensions remote: Fetching raabro 1.4.0 remote: Installing raabro 1.4.0 remote: Fetching stringio 3.1.2 remote: Installing stringio 3.1.2 with native extensions remote: Fetching io-console 0.7.2 remote: Installing io-console 0.7.2 with native extensions remote: Fetching thor 1.3.2 remote: Installing thor 1.3.2 remote: Fetching net-ssh 7.3.0 remote: Installing net-ssh 7.3.0 remote: Fetching ostruct 0.6.1 remote: Installing ostruct 0.6.1 remote: Fetching pg 1.5.9 remote: Installing pg 1.5.9 with native extensions remote: Fetching thruster 0.1.8 (x86_64-linux) remote: Installing thruster 0.1.8 (x86_64-linux) remote: Fetching i18n 1.14.6 remote: Installing i18n 1.14.6 remote: Fetching tzinfo 2.0.6 remote: Installing tzinfo 2.0.6 remote: Fetching rack-session 2.0.0 remote: Installing rack-session 2.0.0 remote: Fetching rack-test 2.1.0 remote: Installing rack-test 2.1.0 remote: Fetching rackup 2.2.0 remote: Installing rackup 2.2.0 remote: Fetching websocket-driver 0.7.6 remote: Installing websocket-driver 0.7.6 with native extensions remote: Fetching net-protocol 0.2.2 remote: Installing net-protocol 0.2.2 remote: Fetching nokogiri 1.16.7 (x86_64-linux) remote: Installing nokogiri 1.16.7 (x86_64-linux) remote: Fetching puma 6.4.3 remote: Installing puma 6.4.3 with native extensions remote: Fetching bootsnap 1.18.4 remote: Installing bootsnap 1.18.4 with native extensions remote: Fetching psych 5.2.0 remote: Installing psych 5.2.0 with native extensions remote: Fetching net-scp 4.0.0 remote: Installing net-scp 4.0.0 remote: Fetching net-sftp 4.0.0 remote: Installing net-sftp 4.0.0 remote: Fetching reline 0.5.11 remote: Installing reline 0.5.11 remote: Fetching et-orbi 1.2.11 remote: Installing et-orbi 1.2.11 remote: Fetching net-pop 0.1.2 remote: Installing net-pop 0.1.2 remote: Fetching net-smtp 0.5.0 remote: Installing net-smtp 0.5.0 remote: Fetching net-imap 0.5.1 remote: Installing net-imap 0.5.1 remote: Fetching loofah 2.23.1 remote: Installing loofah 2.23.1 remote: Fetching activesupport 8.0.0 remote: Installing activesupport 8.0.0 remote: Fetching sshkit 1.23.2 remote: Installing sshkit 1.23.2 remote: Fetching fugit 1.11.1 remote: Installing fugit 1.11.1 remote: Fetching mail 2.8.1 remote: Installing mail 2.8.1 remote: Fetching rails-html-sanitizer 1.6.0 remote: Installing rails-html-sanitizer 1.6.0 remote: Fetching rails-dom-testing 2.2.0 remote: Installing rails-dom-testing 2.2.0 remote: Fetching globalid 1.2.1 remote: Installing globalid 1.2.1 remote: Fetching activemodel 8.0.0 remote: Installing activemodel 8.0.0 remote: Fetching kamal 2.3.0 remote: Installing kamal 2.3.0 remote: Fetching actionview 8.0.0 remote: Installing actionview 8.0.0 remote: Fetching activejob 8.0.0 remote: Installing activejob 8.0.0 remote: Fetching activerecord 8.0.0 remote: Installing activerecord 8.0.0 remote: Fetching actionpack 8.0.0 remote: Installing actionpack 8.0.0 remote: Fetching jbuilder 2.13.0 remote: Installing jbuilder 2.13.0 remote: Fetching actioncable 8.0.0 remote: Installing actioncable 8.0.0 remote: Fetching activestorage 8.0.0 remote: Installing activestorage 8.0.0 remote: Fetching actionmailer 8.0.0 remote: Installing actionmailer 8.0.0 remote: Fetching actionmailbox 8.0.0 remote: Installing actionmailbox 8.0.0 remote: Fetching actiontext 8.0.0 remote: Installing actiontext 8.0.0 remote: Fetching rdoc 6.7.0 remote: Installing rdoc 6.7.0 remote: Fetching irb 1.14.1 remote: Installing irb 1.14.1 remote: Fetching railties 8.0.0 remote: Installing railties 8.0.0 remote: Fetching importmap-rails 2.0.3 remote: Fetching propshaft 1.1.0 remote: Installing importmap-rails 2.0.3 remote: Installing propshaft 1.1.0 remote: Fetching rails 8.0.0 remote: Installing rails 8.0.0 remote: Fetching solid_cable 3.0.2 remote: Fetching solid_cache 1.0.6 remote: Installing solid_cable 3.0.2 remote: Installing solid_cache 1.0.6 remote: Fetching solid_queue 1.0.1 remote: Fetching stimulus-rails 1.3.4 remote: Installing solid_queue 1.0.1 remote: Installing stimulus-rails 1.3.4 remote: Fetching turbo-rails 2.0.11 remote: Installing turbo-rails 2.0.11 remote: Bundle complete! 21 Gemfile dependencies, 86 gems now installed. remote: Gems in the groups 'development' and 'test' were not installed. remote: Bundled gems are installed into `./vendor/bundle` remote: Post-install message from i18n: remote: PSA: I18n will be dropping support for Ruby < 3.2 in the next major release (April 2025), due to Ruby's end of life for 3.1 and below (https://endoflife.date/ruby). Please upgrade to Ruby 3.2 or newer by April 2025 to continue using future versions of this gem. remote: Post-install message from solid_cache: remote: Upgrading from Solid Cache v0.3 or earlier? There are new database migrations in v0.4. remote: See https://github.com/rails/solid_cache/blob/main/upgrading_to_version_0.4.x.md for upgrade instructions. remote: Post-install message from solid_queue: remote: Upgrading to Solid Queue 0.9.0? There are some breaking changes about how recurring tasks are configured. remote: remote: Upgrading to Solid Queue 0.8.0 from < 0.6.0? You need to upgrade to 0.6.0 first. remote: remote: Upgrading to Solid Queue 0.4.x, 0.5.x, 0.6.x or 0.7.x? There are some breaking changes about how Solid Queue is started, remote: configuration and new migrations. remote: remote: --> Check https://github.com/rails/solid_queue/blob/main/UPGRADING.md remote: for upgrade instructions. remote: Bundle completed (21.75s) remote: Cleaning up the bundler cache. remote: -----> Detecting rake tasks remote: -----> Preparing app for Rails asset pipeline remote: Running: rake assets:precompile remote: Writing application-8b441ae0.css remote: Writing stimulus-autoloader-9d447422.js remote: Writing stimulus-importmap-autoloader-64cc03e1.js remote: Writing stimulus-loading-1fc53fe7.js remote: Writing stimulus-d59b3b7f.js remote: Writing stimulus.min-4b1e420e.js remote: Writing stimulus.min-2395e199.js.map remote: Writing turbo-86e38c3c.js remote: Writing turbo.min-fae85750.js remote: Writing turbo.min-5dd5a71a.js.map remote: Writing actiontext.esm-f1c04d34.js remote: Writing actiontext-a4ee937e.js remote: Writing trix-4f753c97.js remote: Writing trix-c4e7be2d.css remote: Writing action_cable-5212cfee.js remote: Writing actioncable.esm-e0ec9819.js remote: Writing actioncable-ac25813f.js remote: Writing activestorage.esm-f2909226.js remote: Writing activestorage-32201f68.js remote: Writing rails-ujs.esm-e925103b.js remote: Writing rails-ujs-20eaf715.js remote: Writing controllers/hello_controller-708796bd.js remote: Writing controllers/index-ee64e1f1.js remote: Writing controllers/application-3affb389.js remote: Writing application-bfcdf840.js remote: Asset precompilation completed (0.84s) remote: Cleaning assets remote: Running: rake assets:clean remote: -----> Detecting rails configuration remote: remote: remote: -----> Discovering process types remote: Procfile declares types -> web remote: Default types for buildpack -> console, rake remote: remote: -----> Compressing... remote: Done: 49.3M remote: -----> Launching... remote: Released v4 remote: https://sleepy-lake-73349-75b72c5796f5.herokuapp.com/ deployed to Heroku remote: remote: Verifying deploy... done. To https://git.heroku.com/sleepy-lake-73349.git * [new branch] main -> main 出力に警告やエラーメッセージが表示された場合は、出力をチェックして、調整します。
デプロイが成功したら、必要に応じて以下のタスクを実行します。
- データベースの移行
- dyno のスケーリング
- 問題が発生した場合はアプリのログのチェック
データベースの移行
アプリケーションでデータベースを使用している場合は、Heroku CLI を使用して、One-off dyno を起動し、移行をトリガーします。One-off dyno で、heroku run コマンドを使ってコマンド (通常はアプリの一部を構成するスクリプトやアプリケーション) を実行できます。次のコマンドでデータベース移行をトリガーできます。
$ heroku run rake db:migrate 代わりに対話型シェルを使用するには、heroku run bash を実行できます。
アプリケーションのスケーリングとアクセス
Heroku は、定義されたプロセスとプロセスタイプを使用してアプリケーションコードを実行します。新しいアプリケーションでは、デフォルトでプロセスタイプがアクティブになりません。次のコマンドはアプリを最大 1 つの dyno にスケーリングし、web プロセスを実行します。
$ heroku ps:scale web=1 Heroku CLI の ps コマンドを使用して、アプリのすべての dyno の状態をターミナルに表示します。
$ heroku ps === web (Basic): bundle exec puma -C config/puma.rb (1) web.1: up 2024/11/13 09:12:02 -0600 (~ 6s ago) この例では、1 つの web プロセスが実行されています。
Eco にサブスクライブしている場合、アプリではデフォルトで Eco dyno が使用されます。それ以外の場合は、デフォルトで Basic dyno が使用されます。Eco dyno プランは、アカウントのすべての Eco dyno 間で共有され、多数の小さなアプリを Heroku にデプロイする場合にお勧めします。Eco dyno は 30 分間トラフィックを何も受信しないとスリープします。このスリープ動作により、スリープ解除した最初のリクエストで数秒の遅延が発生します。Eco dyno は、月ごとに割り当てられるアカウント別の Eco dyno 時間を消費します。割り当て時間が残っている限り、アプリは稼働し続けます。
dyno がスリープしないようにするには、「dyno タイプ」の記事で紹介されている Basic 以上の dyno タイプにアップグレードします。少なくとも Standard dyno にアップグレードすることでも、プロセスタイプあたり複数の dyno にスケールアップできます。
アプリをブラウザで開くには、heroku open を実行します。
$ heroku open ブラウザに、「Hello World」というテキストが表示されます。表示されない場合、またはエラーが発生した場合は、ウェルカムページのコンテンツをレビューして確認してください。
Heroku では、開発中のすべてのアプリケーションにデフォルトの Web URL が提供されます。アプリケーションを本番環境用に準備できたら、カスタムドメインを追加します。
アプリケーションログの表示
アプリが正しく実行されないか、またはエラーを生成する場合、アプリログは貴重なツールです。
実行中のアプリに関する情報は、Heroku CLI のログ記録コマンド heroku logs を使用して表示します。出力例を次に示します。
$ heroku logs 2024-11-13T15:11:59.943576+00:00 heroku[web.1]: Starting process with command `bundle exec puma -C config/puma.rb` 2024-11-13T15:12:00.721350+00:00 app[web.1]: Puma starting in single mode... 2024-11-13T15:12:00.721367+00:00 app[web.1]: * Puma version: 6.4.3 (ruby 3.2.6-p234) ("The Eagle of Durango") 2024-11-13T15:12:00.721367+00:00 app[web.1]: * Min threads: 3 2024-11-13T15:12:00.721368+00:00 app[web.1]: * Max threads: 3 2024-11-13T15:12:00.721368+00:00 app[web.1]: * Environment: production 2024-11-13T15:12:00.721384+00:00 app[web.1]: * PID: 2 2024-11-13T15:12:02.751909+00:00 app[web.1]: * Listening on http://0.0.0.0:51767 2024-11-13T15:12:02.754052+00:00 app[web.1]: Use Ctrl-C to stop 2024-11-13T15:12:02.778173+00:00 heroku[web.1]: State changed from starting to up 2024-11-13T15:12:10.600072+00:00 app[web.1]: [b4650052-7f2a-4ae5-99ee-d42b21e67d0c] Started GET "/" for 204.14.236.210 at 2024-11-13 15:12:10 +0000 2024-11-13T15:12:10.602074+00:00 app[web.1]: [b4650052-7f2a-4ae5-99ee-d42b21e67d0c] Processing by WelcomeController#index as HTML 2024-11-13T15:12:10.618901+00:00 app[web.1]: [b4650052-7f2a-4ae5-99ee-d42b21e67d0c] Rendered layout layouts/application.html.erb (Duration: 6.4ms | GC: 0.6ms) 2024-11-13T15:12:10.619103+00:00 app[web.1]: [b4650052-7f2a-4ae5-99ee-d42b21e67d0c] Completed 200 OK in 17ms (Views: 7.0ms | ActiveRecord: 0.0ms (0 queries, 0 cached) | GC: 1.1ms) 2024-11-13T15:12:10.620721+00:00 heroku[router]: at=info method=GET path="/" host=sleepy-lake-73349-75b72c5796f5.herokuapp.com request_id=b4650052-7f2a-4ae5-99ee-d42b21e67d0c fwd="204.14.236.210" dyno=web.1 connect=0ms service=22ms status=200 bytes=2944 protocol=https 2024-11-13T15:12:10.674598+00:00 heroku[router]: at=info method=GET path="/assets/application-8b441ae0.css" host=sleepy-lake-73349-75b72c5796f5.herokuapp.com request_id=d234470d-9961-4a43-8a38-461a94e875b0 fwd="204.14.236.210" dyno=web.1 connect=0ms service=1ms status=200 bytes=725 protocol=https 2024-11-13T15:12:10.705544+00:00 heroku[router]: at=info method=GET path="/assets/application-bfcdf840.js" host=sleepy-lake-73349-75b72c5796f5.herokuapp.com request_id=aa6666a0-c59a-4200-a9a8-1f4113f3cc3c fwd="204.14.236.210" dyno=web.1 connect=0ms service=1ms status=200 bytes=398 protocol=https 2024-11-13T15:12:10.729602+00:00 heroku[router]: at=info method=GET path="/assets/stimulus.min-4b1e420e.js" host=sleepy-lake-73349-75b72c5796f5.herokuapp.com request_id=02785a18-11ce-4913-ada8-81f4378e1268 fwd="204.14.236.210" dyno=web.1 connect=0ms service=2ms status=200 bytes=45900 protocol=https 2024-11-13T15:12:10.733494+00:00 heroku[router]: at=info method=GET path="/assets/stimulus-loading-1fc53fe7.js" host=sleepy-lake-73349-75b72c5796f5.herokuapp.com request_id=cc2e1287-46cf-46ee-8702-081cf886a64d fwd="204.14.236.210" dyno=web.1 connect=0ms service=1ms status=200 bytes=3557 protocol=https 2024-11-13T15:12:10.735514+00:00 heroku[router]: at=info method=GET path="/assets/turbo.min-fae85750.js" host=sleepy-lake-73349-75b72c5796f5.herokuapp.com request_id=f0339fd0-d962-4e4d-ab7b-ec3050062303 fwd="204.14.236.210" dyno=web.1 connect=0ms service=1ms status=200 bytes=104283 protocol=https 2024-11-13T15:12:10.744800+00:00 heroku[router]: at=info method=GET path="/assets/controllers/hello_controller-708796bd.js" host=sleepy-lake-73349-75b72c5796f5.herokuapp.com request_id=90d62558-8be2-434f-922b-ed001d57a405 fwd="204.14.236.210" dyno=web.1 connect=0ms service=0ms status=200 bytes=398 protocol=https 2024-11-13T15:12:10.745304+00:00 heroku[router]: at=info method=GET path="/assets/controllers/application-3affb389.js" host=sleepy-lake-73349-75b72c5796f5.herokuapp.com request_id=aa5edfd7-bc8a-427f-be6a-32385c5ed7ff fwd="204.14.236.210" dyno=web.1 connect=0ms service=1ms status=200 bytes=459 protocol=https 2024-11-13T15:12:10.749834+00:00 heroku[router]: at=info method=GET path="/assets/controllers/index-ee64e1f1.js" host=sleepy-lake-73349-75b72c5796f5.herokuapp.com request_id=a1c86c2b-9dc8-468e-a7ec-b72234fba972 fwd="204.14.236.210" dyno=web.1 connect=0ms service=0ms status=200 bytes=513 protocol=https 2024-11-13T15:12:10.953738+00:00 heroku[router]: at=info method=GET path="/icon.svg" host=sleepy-lake-73349-75b72c5796f5.herokuapp.com request_id=6c1305e9-e440-4956-adc2-c4b5c562008c fwd="204.14.236.210" dyno=web.1 connect=0ms service=1ms status=200 bytes=361 protocol=https 2024-11-13T15:12:11.037536+00:00 heroku[router]: at=info method=GET path="/icon.png" host=sleepy-lake-73349-75b72c5796f5.herokuapp.com request_id=ec2bc8f8-7361-4b93-97a5-cdf22eb438af fwd="204.14.236.210" dyno=web.1 connect=0ms service=1ms status=200 bytes=4402 protocol=https アプリのログの完全なライブストリームを表示するには、コマンドに -t/--tail を追加します。
$ heroku logs --tail Heroku では、デフォルトで 1500 行のアプリケーションログが記録されますが、完全なログストリームはサービスとして提供されています。複数のアドオンプロバイダが、ログの永続化、検索、メールや SMS 通知などの機能を提供するログサービスを用意しています。
オプションのステップ
Rails コンソールの使用
One-off dyno をトリガーして、スクリプトやアプリケーションを必要な場合にのみ実行するには、Heroku CLI の run コマンドを使用します。このコマンドを使用して、アプリの環境で試行するためにローカルターミナルにアタッチされた Rails コンソールプロセスを起動します。
$ heroku run rails console irb(main):001:0> puts 1+1 2 また、run bash Heroku CLI コマンドもデバッグに役立ちます。このコマンドは、対話型の bash セッションで新しい One-off dyno を起動します。
Rake コマンドの実行
Rails コンソールと同様に、run コマンドを使用して、db:migrate などの rake コマンドを実行します。
$ heroku run rake db:migrate Procfile をローカルで使用する
Procfile をローカルで使用するには、heroku local CLI コマンドを使用します。
Procfile でのコマンドの実行に加えて、heroku local コマンドでは、環境変数を .env ファイル経由でローカルで管理することもできます。RACK_ENVを、ローカル環境の場合は development に、Puma の場合は PORT に設定します。
$ echo "RACK_ENV=development" >>.env $ echo "PORT=3000" >> .env .env ファイルを使用して環境変数をローカルで使用する代わりの方法として dotenv gem があります。
これらの変数はローカル環境の設定専用であるため、.env を .gitignore に追加します。
$ echo ".env" >> .gitignore $ git add .gitignore $ git commit -m "add .env to .gitignore" Foreman を使用して、Procfile をローカルでテストします。localを使用して Web サーバーを起動します。
$ heroku local [OKAY] Loaded ENV .env File as KEY=VALUE Format 9:12:15 AM web.1 | Puma starting in single mode... 9:12:15 AM web.1 | * Puma version: 6.4.3 (ruby 3.2.6-p234) ("The Eagle of Durango") 9:12:15 AM web.1 | * Min threads: 3 9:12:15 AM web.1 | * Max threads: 3 9:12:15 AM web.1 | * Environment: development 9:12:15 AM web.1 | * PID: 98056 9:12:15 AM web.1 | * Listening on http://0.0.0.0:3000 9:12:15 AM web.1 | Use Ctrl-C to stop Ctrl+C または Cmd+C を押して終了します。
トラブルシューティング
たとえば heroku ps に crashed 状態が表示されるなど、Heroku にデプロイされたアプリがクラッシュした場合は、アプリのログを確認します。次のセクションでは、アプリのクラッシュの一般的な原因について説明します。
開発またはテスト gem でのランタイムの依存関係
デプロイ中に gem が存在しない場合は、Bundler グループをチェックしてください。Heroku では、アプリが development または test グループなしでビルドされ、アプリの実行をこれらのいずれかのグループの gem に依存している場合は、それをグループから除外します。
一般的な例として、Rakefile での RSpec タスクの使用があります。このエラーは多くの場合、次のようになります。
$ heroku run rake -T Running `bundle exec rake -T` attached to terminal... up, ps.3 rake aborted! no such file to load -- rspec/core/rake_task まず、開発またはテスト gem グループなしで bundle install を実行して、問題をローカルに複製します。
$ bundle install --without development:test … $ bundle exec rake -T rake aborted! no such file to load -- rspec/core/rake_task bundler の --without オプションは永続的です。このオプションを削除するには、bundle config --delete without を実行します。
これらの Rake タスクを gem のロード中に条件付きにすることによってエラーを解決します。たとえば、次のようになります。
begin require "rspec/core/rake_task" desc "Run all examples" RSpec::Core::RakeTask.new(:spec) do |t| t.rspec_opts = %w[--color] t.pattern = 'spec/**/*_spec.rb' end rescue LoadError end これがローカルで動作することを確認してから、Heroku にプッシュします。
次のステップ
Rails 8 アプリケーションをデプロイできました。調査を継続するには、次に、以下の記事を確認してください。
- 「Ruby サポートカテゴリ」では、Heroku での Ruby および Rails の使用に関する詳細を確認できます。
- 「デプロイカテゴリ」では、デプロイを効率的かつ簡単に行うことができるようにする、多くの強力な統合や機能を紹介しています。
コストを抑制するために、チュートリアルを完了したらすぐにサンプルアプリを削除し、データベースも削除してください。
アプリとアドオンを削除する
アカウントからアプリとデータベースを削除します。使用したリソースに対してのみ課金されます。
この操作により、アドオンとデータベースに保存されたすべてのデータが削除されます。
$ heroku addons:destroy heroku-postgresql この操作により、アプリケーションが完全に削除されます。
$ heroku apps:destroy 以下のコマンドによって、アドオンとアプリが消去されたことを確認できます。
$ heroku addons --all $ heroku apps --all これで、アプリをデプロイする準備ができました。