Heroku スターターガイド (Rails 6.x)
この記事の英語版に更新があります。ご覧の翻訳には含まれていない変更点があるかもしれません。
最終更新日 2023年02月06日(月)
Table of Contents
Heroku dyno、Heroku Postgres、および Heroku Data for Redis の無料プランは 2022 年 11 月 28 日で提供を終了します。資格のある学生の皆様は、新しい Heroku for GitHub Students プログラムを通じてプラットフォームクレジットを申請できます。
Rails の利用可能な最新バージョンは Rails 7 です。新しいアプリケーションを開始する場合は、最新リリースバージョンを使用することをお勧めします。
Ruby on Rails は、Ruby で記述され、広く使われている Web フレームワークです。このガイドでは、Heroku での Rails 6 の使用について説明します。Heroku での Rails 旧バージョンの実行についての詳細は、Rails 5.x または Rails 4.x に関するチュートリアルを参照してください。
このガイドでは、以下が必要となります。
- Ruby/Rails および Git の基本的な知識
- Ruby 2.5.0+、Rubygems、Bundler、Rails 6 のローカルにインストールされたバージョン+
- 確認済みの Heroku アカウント
- Eco dyno プランのサブスクリプション (推奨)
ローカルの設定
Heroku CLI を開発用マシンにインストールします。
インストールされたら、heroku
コマンドをターミナルから利用できます。Heroku アカウントのメールアドレスとパスワードを使用してログインします。
$ heroku login
heroku: Enter your Heroku credentials
Email: schneems@example.com
Password:
Could not find an existing public key.
Would you like to generate one? [Yn]
Generating new SSH public key.
Uploading ssh public key /Users/adam/.ssh/id_rsa.pub
プロンプトで Enter キーを押し、後でコードのプッシュに使用するため、既存の ssh
キーをアップロードするか新しいキーを作成します。
新しい Rails アプリの作成 (または既存の Rails アプリのアップグレード)
新しいアプリを作成するには、最初に、rails -v
を実行して、Rails 6.x を使用していることを確認してください。必要に応じて、Rails の新しいバージョンは、以下を実行すると取得できます。
$ gem install rails -v 6.1.1 --no-document
Successfully installed rails-6.1.1
1 gem installed
続いて新しいアプリを作成し、ルートディレクトリに移動します。
$ rails _6.1.1_ new myapp --database=postgresql
作成したら、アプリケーションのディレクトリに移動します。
$ cd myapp
$ bundle lock --add-platform x86_64-linux --add-platform ruby
The dependency tzinfo-data (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mingw32, x86-mswin32, x64-mingw32, java. To add those platforms to the bundle, run `bundle lock --add-platform x86-mingw32 x86-mswin32 x64-mingw32 java`.
Fetching gem metadata from https://rubygems.org/..........
Writing lockfile to ./myapp/Gemfile.lock
ローカルでデータベースを作成します。
$ bin/rails db:create
Database 'myapp_development' already exists
pg gem の追加
--database=postgresql
を指定せずに作成された既存のアプリを使用している場合は、Rails プロジェクトに pg
gem を追加する必要があります。Gemfile
を編集し、以下の行を変更します。
gem 'sqlite3'
変更後は次のようになります。
gem 'pg'
開発には PostgreSQL を使用することを強くお勧めします。処理中の開発と開発環境を一致させることで、環境の違いによる微妙なバグの発生が阻止されます。Postgres はローカルにインストールしてください (まだシステムにない場合)。
(新しい Gemfile.lock
を生成するために) 依存関係を再インストールします。
$ bundle install
Sqlite3 の代わりに Postgres を推奨する理由に関する詳細は、「why you cannot use Sqlite3 on Heroku」(Heroku で Sqlite3 を使用できない理由) を参照してください。
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 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 } %>
development:
<<: *default
database: myapp_development
# The specified database role being used to connect to postgres.
# To create additional roles in postgres see `$ createuser --help`.
# When left blank, postgres will use the default role. This is
# the same name as the operating system user running Rails.
#username: myapp
# The password associated with the postgres 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:
<<: *default
database: myapp_production
username: myapp
password: <%= ENV["MYAPP_DATABASE_PASSWORD"] %>
ここで注意点があります。adapter
セクションの postgresql
の末尾で sql
を省略すると、アプリケーションは機能しません。
ウェルカムページの作成
Rails 6 の本番環境には、デフォルトで静的なインデックスページがありません。新しいアプリを使用するとき、本番環境にはルートページがないため、ルートページを作成する必要があります。最初に、welcome
と呼ばれるコントローラーを作成し、ホームページが本番稼働します。
$ rails generate controller welcome
次に、インデックスページを追加します。
ファイル app/views/welcome/index.html.erb
で、以下のように記述します。
<h2>Hello World</h2>
<p>
The time is now: <%= Time.now %>
</p>
その後、Rails をこのアクションにルーティングする必要があります。config/routes.rb
を編集して、新しいメソッドにインデックスページを設定します。
ファイル config/routes.rb
の 2 行目に以下を追加します。
root 'welcome#index'
サーバーを実行して、このページが存在することを検証できます。
$ rails server
さらに、ブラウザで http://localhost:3000 にアクセスします。ページが表示されない場合、サーバーに出力されたログを使用してデバッグします。
Heroku gem
以前のバージョンの Rails では、Heroku で静的アセットの提供やログ記録を有効にするには、プロジェクト rails_12factor に gem を追加する必要がありました。新しいアプリケーションをデプロイしている場合、この gem は必要ありません。既存のアプリケーションをアップグレードしているときは、config/environments/production.rb
ファイルに適切な設定がある場合、この gem を削除できます。
# config/environments/production.rb
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
Ruby バージョンの指定
Rails 6 では、Ruby 2.5.0 以上が必要です。Heroku にはデフォルトで Ruby の最新バージョンがインストールされていますが、Gemfile
で ruby
DSL を使用して、特定のバージョンを指定できます。現在実行している Ruby のバージョンに応じて、次のように表示されます。
ruby "2.7.2"
同じ Ruby のバージョンをローカルでも実行している必要があります。$ ruby -v
を実行することによりこれを確認できます。ここから、Heroku での Ruby バージョンの指定に関する詳細を確認できます。
Git でのアプリの保存
Heroku では、プロジェクトのデプロイを分散型ソース管理ツールである Git に依存しています。プロジェクトがまだ Git で管理されていない場合は、システムに git
があることを検証してください。
$ git --help
usage: git [--version] [--help] [-C <path>] [-c <name>=<value>]
[--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
[-p | --paginate | -P | --no-pager] [--no-replace-objects] [--bare]
[--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
[--super-prefix=<path>] [--config-env=<name>=<envvar>]
出力がない、または command not found
が出力される場合は、Git をシステムにインストールする必要があります。
Git が機能することを検証した後、$ ls
を実行して Rails アプリのディレクトリにいることを確認してください。
出力は以下のようになります。
$ ls
Gemfile
Gemfile-e
Gemfile.lock
README.md
Rakefile
app
bin
config
config.ru
db
lib
log
public
storage
test
tmp
vendor
次に、Rails アプリのディレクトリで以下のコマンドを実行し、コードを初期化して Git にコミットします。
$ git init
$ git add .
$ git commit -m "init"
以下を実行し、すべてが正しくコミットしているかどうかを確認できます。
$ git status
On branch main
nothing to commit, working tree clean
アプリケーションが Git にコミットされ、Heroku にデプロイできるようになりました。
Heroku へのアプリケーションのデプロイ
Rails アプリが含まれるディレクトリにいることを確認してから、Heroku でアプリを作成します。
$ heroku create --stack heroku-20
Creating app... done, evening-refuge-08950, stack is heroku-20
https://evening-refuge-08950.herokuapp.com/ | https://git.heroku.com/evening-refuge-08950.git
以下を実行して、リモートがプロジェクトに追加されていることを確認できます。
$ git config --list --local | grep heroku
remote.heroku.url=https://git.heroku.com/evening-refuge-08950.git
remote.heroku.fetch=+refs/heads/*:refs/remotes/heroku/*
fatal: not in a git directory
が表示される場合は、ディレクトリが正しくない可能性があります。表示されなければ、コードをデプロイできます。コードをデプロイした後、データベースを移行する必要があります。データベースが適切にスケールされていることを確認し、問題はログを使用してすべてデバッグしてください。
業界での変更に従い、Heroku ではデフォルトの Git ブランチ名を main
に変更しました。デプロイ中のプロジェクトでデフォルトのブランチ名として master
を使用している場合は、git push heroku master
を使用してください。
コードをデプロイします。
$ git push heroku main
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Building on the Heroku-20 stack
remote: ! Warning: Multiple default buildpacks reported the ability to handle this app. The first buildpack in the list below will be used.
remote: Detected buildpacks: Ruby,Node.js
remote: See https://devcenter.heroku.com/articles/buildpacks#buildpack-detect-order
remote: -----> Ruby app detected
remote: -----> Installing bundler 2.1.4
remote: -----> Removing BUNDLED WITH version in the Gemfile.lock
remote: -----> Compiling Ruby/Rails
remote: -----> Using Ruby version: ruby-2.7.2
remote: -----> Installing dependencies using bundler 2.1.4
remote: Running: BUNDLE_WITHOUT='development:test' BUNDLE_PATH=vendor/bundle BUNDLE_BIN=vendor/bundle/bin BUNDLE_DEPLOYMENT=1 bundle install -j4
remote: The dependency tzinfo-data (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mingw32, x86-mswin32, x64-mingw32, java. To add those platforms to the bundle, run `bundle lock --add-platform x86-mingw32 x86-mswin32 x64-mingw32 java`.
remote: Fetching gem metadata from https://rubygems.org/............
remote: Fetching rake 13.0.3
remote: Installing rake 13.0.3
remote: Fetching concurrent-ruby 1.1.8
remote: Fetching zeitwerk 2.4.2
remote: Fetching minitest 5.14.3
remote: Installing zeitwerk 2.4.2
remote: Installing minitest 5.14.3
remote: Installing concurrent-ruby 1.1.8
remote: Fetching builder 3.2.4
remote: Installing builder 3.2.4
remote: Fetching erubi 1.10.0
remote: Installing erubi 1.10.0
remote: Fetching mini_portile2 2.5.0
remote: Fetching racc 1.5.2
remote: Installing mini_portile2 2.5.0
remote: Installing racc 1.5.2 with native extensions
remote: Fetching crass 1.0.6
remote: Installing crass 1.0.6
remote: Fetching rack 2.2.3
remote: Installing rack 2.2.3
remote: Fetching nio4r 2.5.5
remote: Installing nio4r 2.5.5 with native extensions
remote: Fetching websocket-extensions 0.1.5
remote: Installing websocket-extensions 0.1.5
remote: Fetching mimemagic 0.3.5
remote: Installing mimemagic 0.3.5
remote: Fetching mini_mime 1.0.2
remote: Installing mini_mime 1.0.2
remote: Fetching msgpack 1.4.2
remote: Installing msgpack 1.4.2 with native extensions
remote: Using bundler 2.1.4
remote: Fetching ffi 1.14.2
remote: Installing ffi 1.14.2 with native extensions
remote: Fetching method_source 1.0.0
remote: Installing method_source 1.0.0
remote: Fetching pg 1.2.3
remote: Installing pg 1.2.3 with native extensions
remote: Fetching thor 1.1.0
remote: Installing thor 1.1.0
remote: Fetching tilt 2.0.10
remote: Installing tilt 2.0.10
remote: Fetching semantic_range 2.3.1
remote: Installing semantic_range 2.3.1
remote: Fetching turbolinks-source 5.2.0
remote: Installing turbolinks-source 5.2.0
remote: Fetching i18n 1.8.8
remote: Installing i18n 1.8.8
remote: Fetching tzinfo 2.0.4
remote: Installing tzinfo 2.0.4
remote: Fetching rack-test 1.1.0
remote: Installing rack-test 1.1.0
remote: Fetching rack-proxy 0.6.5
remote: Installing rack-proxy 0.6.5
remote: Fetching sprockets 4.0.2
remote: Installing sprockets 4.0.2
remote: Fetching websocket-driver 0.7.3
remote: Installing websocket-driver 0.7.3 with native extensions
remote: Fetching marcel 0.3.3
remote: Installing marcel 0.3.3
remote: Fetching mail 2.7.1
remote: Installing mail 2.7.1
remote: Fetching nokogiri 1.11.1 (x86_64-linux)
remote: Installing nokogiri 1.11.1 (x86_64-linux)
remote: Fetching puma 5.2.1
remote: Installing puma 5.2.1 with native extensions
remote: Fetching bootsnap 1.7.2
remote: Installing bootsnap 1.7.2 with native extensions
remote: Fetching turbolinks 5.2.1
remote: Installing turbolinks 5.2.1
remote: Fetching activesupport 6.1.1
remote: Installing activesupport 6.1.1
remote: Fetching sassc 2.4.0
remote: Installing sassc 2.4.0 with native extensions
remote: Fetching loofah 2.9.0
remote: Installing loofah 2.9.0
remote: Fetching rails-dom-testing 2.0.3
remote: Installing rails-dom-testing 2.0.3
remote: Fetching globalid 0.4.2
remote: Installing globalid 0.4.2
remote: Fetching activemodel 6.1.1
remote: Installing activemodel 6.1.1
remote: Fetching jbuilder 2.11.2
remote: Installing jbuilder 2.11.2
remote: Fetching rails-html-sanitizer 1.3.0
remote: Installing rails-html-sanitizer 1.3.0
remote: Fetching activejob 6.1.1
remote: Installing activejob 6.1.1
remote: Fetching activerecord 6.1.1
remote: Installing activerecord 6.1.1
remote: Fetching actionview 6.1.1
remote: Installing actionview 6.1.1
remote: Fetching actionpack 6.1.1
remote: Installing actionpack 6.1.1
remote: Fetching actioncable 6.1.1
remote: Fetching activestorage 6.1.1
remote: Installing actioncable 6.1.1
remote: Installing activestorage 6.1.1
remote: Fetching actionmailer 6.1.1
remote: Installing actionmailer 6.1.1
remote: Fetching railties 6.1.1
remote: Fetching sprockets-rails 3.2.2
remote: Installing railties 6.1.1
remote: Installing sprockets-rails 3.2.2
remote: Fetching actionmailbox 6.1.1
remote: Installing actionmailbox 6.1.1
remote: Fetching actiontext 6.1.1
remote: Installing actiontext 6.1.1
remote: Fetching rails 6.1.1
remote: Fetching webpacker 5.2.1
remote: Installing rails 6.1.1
remote: Installing webpacker 5.2.1
remote: Fetching sassc-rails 2.1.2
remote: Installing sassc-rails 2.1.2
remote: Fetching sass-rails 6.0.0
remote: Installing sass-rails 6.0.0
remote: Bundle complete! 17 Gemfile dependencies, 58 gems now installed.
remote: Gems in the groups development and test were not installed.
remote: Bundled gems are installed into `./vendor/bundle`
remote: Bundle completed (256.66s)
remote: Cleaning up the bundler cache.
remote: -----> Installing node-v12.16.2-linux-x64
remote: -----> Installing yarn-v1.22.4
remote: -----> Detecting rake tasks
remote: -----> Preparing app for Rails asset pipeline
remote: Running: rake assets:precompile
remote: yarn install v1.22.4
remote: [1/4] Resolving packages...
remote: [2/4] Fetching packages...
remote: info fsevents@2.3.2: The platform "linux" is incompatible with this module.
remote: info "fsevents@2.3.2" is an optional dependency and failed compatibility check. Excluding it from installation.
remote: info fsevents@1.2.13: The platform "linux" is incompatible with this module.
remote: info "fsevents@1.2.13" is an optional dependency and failed compatibility check. Excluding it from installation.
remote: [3/4] Linking dependencies...
remote: warning " > webpack-dev-server@3.11.2" has unmet peer dependency "webpack@^4.0.0 || ^5.0.0".
remote: warning "webpack-dev-server > webpack-dev-middleware@3.7.3" has unmet peer dependency "webpack@^4.0.0 || ^5.0.0".
remote: [4/4] Building fresh packages...
remote: Done in 26.41s.
remote: I, [2021-02-08T21:38:56.635373 #1401] INFO -- : Writing /tmp/build_c9eb17d5/public/assets/manifest-b4bf6e57a53c2bdb55b8998cc94cd00883793c1c37c5e5aea3ef6749b4f6d92b.js
remote: I, [2021-02-08T21:38:56.635690 #1401] INFO -- : Writing /tmp/build_c9eb17d5/public/assets/manifest-b4bf6e57a53c2bdb55b8998cc94cd00883793c1c37c5e5aea3ef6749b4f6d92b.js.gz
remote: I, [2021-02-08T21:38:56.635944 #1401] INFO -- : Writing /tmp/build_c9eb17d5/public/assets/application-04024382391bb910584145d8113cf35ef376b55d125bb4516cebeb14ce788597.css
remote: I, [2021-02-08T21:38:56.636153 #1401] INFO -- : Writing /tmp/build_c9eb17d5/public/assets/application-04024382391bb910584145d8113cf35ef376b55d125bb4516cebeb14ce788597.css.gz
remote: I, [2021-02-08T21:38:56.636338 #1401] INFO -- : Writing /tmp/build_c9eb17d5/public/assets/welcome-04024382391bb910584145d8113cf35ef376b55d125bb4516cebeb14ce788597.css
remote: I, [2021-02-08T21:38:56.636632 #1401] INFO -- : Writing /tmp/build_c9eb17d5/public/assets/welcome-04024382391bb910584145d8113cf35ef376b55d125bb4516cebeb14ce788597.css.gz
remote: Compiling...
remote: Compiled all packs in /tmp/build_c9eb17d5/public/packs
remote: Hash: 10775e74720141811436
remote: Version: webpack 4.46.0
remote: Time: 5901ms
remote: Built at: 02/08/2021 9:39:04 PM
remote: Asset Size Chunks Chunk Names
remote: js/application-2d24cb02e79dc1ee88b7.js 69.3 KiB 0 [emitted] [immutable] application
remote: js/application-2d24cb02e79dc1ee88b7.js.br 15.3 KiB [emitted]
remote: js/application-2d24cb02e79dc1ee88b7.js.gz 17.8 KiB [emitted]
remote: js/application-2d24cb02e79dc1ee88b7.js.map 205 KiB 0 [emitted] [dev] application
remote: js/application-2d24cb02e79dc1ee88b7.js.map.br 43.9 KiB [emitted]
remote: js/application-2d24cb02e79dc1ee88b7.js.map.gz 50.9 KiB [emitted]
remote: manifest.json 364 bytes [emitted]
remote: manifest.json.br 126 bytes [emitted]
remote: manifest.json.gz 142 bytes [emitted]
remote: Entrypoint application = js/application-2d24cb02e79dc1ee88b7.js js/application-2d24cb02e79dc1ee88b7.js.map
remote: [0] (webpack)/buildin/module.js 552 bytes {0} [built]
remote: [4] ./app/javascript/packs/application.js 480 bytes {0} [built]
remote: [5] ./app/javascript/channels/index.js 205 bytes {0} [built]
remote: [6] ./app/javascript/channels sync _channel\.js$ 160 bytes {0} [built]
remote: + 3 hidden modules
remote:
remote: Asset precompilation completed (36.52s)
remote: Cleaning assets
remote: Running: rake assets:clean
remote: -----> Detecting rails configuration
remote:
remote: ###### WARNING:
remote:
remote: No Procfile detected, using the default web server.
remote: We recommend explicitly declaring how to boot your server process via a Procfile.
remote: https://devcenter.heroku.com/articles/ruby-default-web-server
remote:
remote:
remote: -----> Discovering process types
remote: Procfile declares types -> (none)
remote: Default types for buildpack -> console, rake, web
remote:
remote: -----> Compressing...
remote: Done: 91.7M
remote: -----> Launching...
remote: Released v6
remote: https://aqueous-sierra-44713.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/aqueous-sierra-44713.git
* [new branch] main -> main
出力に警告やエラーがないかどうかを必ず確認してください。何も問題がなければ、データベースを移行できます。
データベースの移行
アプリケーションでデータベースを使用している場合は、以下を実行して手動でデータベースを移行する必要があります。
$ heroku run rake db:migrate
heroku run
の後のコマンドはすべて Heroku dyno で実行されます。$ heroku run bash
を実行して、対話型シェルセッションを取得できます。
アプリケーションへのアクセス
コードが Heroku にデプロイされ、プロセスタイプを実行するように Heroku に指示できるようになりました。Heroku では、これは dyno (Heroku の構成の基本単位である軽量コンテナ) で関連付けられているコマンドを実行して行われます。
1 つの dyno によって web
プロセスタイプが実行されていることを確認します。
$ heroku ps:scale web=1
アプリの dyno の状態をチェックできます。heroku ps
コマンドにより、アプリケーションで実行中の dyno の一覧が表示されます。
$ heroku ps
Eco dyno hours quota remaining this month: 1000h 0m (100%)
Eco dyno usage for this app: 0h 0m (0%)
For more information on dyno sleeping and how to upgrade, see:
https://devcenter.heroku.com/articles/eco-dyno-hours#dyno-sleeping
=== web (Eco): bin/rails server -p ${PORT:-5000} -e $RAILS_ENV (1)
web.1: starting 2022/11/09 14:50:25 -0800 (~ 8s ago)
ここでは、1 つの dyno が実行中です。
heroku open
を使用して、ブラウザでアプリにアクセスできます。
$ heroku open
すると、先ほど挿入したテキスト「Hello World」が表示されます。
Heroku では、開発中の複雑さをなくすため、デフォルトの URL が提供されます。スケールアップして Heroku を本番環境で使用する準備が整っている場合は、独自のカスタムドメインを追加できます。
ログの表示
アプリが適切に機能しないような問題が発生した場合は、ログをチェックする必要があります。
ログコマンドの 1 つである heroku logs
を使って、実行中のアプリに関する情報を表示できます。
$ heroku logs
2022-11-09T22:49:44.850928+00:00 app[api]: Release v1 created by user developer@example.com2022-11-09T22:49:44.850928+00:00 app[api]: Initial release by user developer@example.com2022-11-09T22:49:46.274267+00:00 app[api]: Enable Logplex by user developer@example.com2022-11-09T22:49:46.274267+00:00 app[api]: Release v2 created by user developer@example.com2022-11-09T22:49:47.000000+00:00 app[api]: Build started by user developer@example.com2022-11-09T22:50:23.536118+00:00 app[api]: Release v3 created by user developer@example.com2022-11-09T22:50:23.536118+00:00 app[api]: Set LANG, RACK_ENV, RAILS_ENV, RAILS_LOG_TO_STDOUT, RAILS_SERVE_STATIC_FILES, SECRET_KEY_BASE config vars by user developer@example.com2022-11-09T22:50:27.675613+00:00 heroku[web.1]: Starting process with command `bin/rails server -p ${PORT:-5000} -e production`
2022-11-09T22:50:31.968636+00:00 app[web.1]: => Booting Puma
2022-11-09T22:50:31.968666+00:00 app[web.1]: => Rails 7.0.4 application starting in production
2022-11-09T22:50:31.968666+00:00 app[web.1]: => Run `bin/rails server --help` for more startup options
2022-11-09T22:50:33.164978+00:00 app[web.1]: Puma starting in single mode...
2022-11-09T22:50:33.165023+00:00 app[web.1]: * Puma version: 5.6.5 (ruby 2.7.2-p137) ("Birdie's Version")
2022-11-09T22:50:33.165024+00:00 app[web.1]: * Min threads: 5
2022-11-09T22:50:33.165024+00:00 app[web.1]: * Max threads: 5
2022-11-09T22:50:33.165024+00:00 app[web.1]: * Environment: production
2022-11-09T22:50:33.165024+00:00 app[web.1]: * PID: 4
2022-11-09T22:50:33.165241+00:00 app[web.1]: * Listening on http://0.0.0.0:21555
2022-11-09T22:50:33.170127+00:00 app[web.1]: Use Ctrl-C to stop
2022-11-09T22:50:33.757292+00:00 heroku[web.1]: State changed from starting to up
2022-11-09T22:50:37.470517+00:00 app[web.1]: I, [2022-11-09T22:50:37.470427 #4] INFO -- : [c5e2bb06-7b65-4353-b336-23455f2eff0b] Started GET "/" for 13.110.54.11 at 2022-11-09 22:50:37 +0000
2022-11-09T22:50:37.474722+00:00 app[web.1]: I, [2022-11-09T22:50:37.474656 #4] INFO -- : [c5e2bb06-7b65-4353-b336-23455f2eff0b] Processing by WelcomeController#index as HTML
2022-11-09T22:50:37.477152+00:00 app[web.1]: I, [2022-11-09T22:50:37.477100 #4] INFO -- : [c5e2bb06-7b65-4353-b336-23455f2eff0b] Rendered welcome/index.html.erb within layouts/application (Duration: 0.6ms | Allocations: 120)
2022-11-09T22:50:37.484352+00:00 app[web.1]: I, [2022-11-09T22:50:37.484285 #4] INFO -- : [c5e2bb06-7b65-4353-b336-23455f2eff0b] Rendered layout layouts/application.html.erb (Duration: 7.8ms | Allocations: 2230)
2022-11-09T22:50:37.484826+00:00 app[web.1]: I, [2022-11-09T22:50:37.484783 #4] INFO -- : [c5e2bb06-7b65-4353-b336-23455f2eff0b] Completed 200 OK in 10ms (Views: 9.3ms | Allocations: 2825)
2022-11-09T22:50:37.486338+00:00 heroku[router]: at=info method=GET path="/" host=evening-refuge-08950.herokuapp.com request_id=c5e2bb06-7b65-4353-b336-23455f2eff0b fwd="13.110.54.11" dyno=web.1 connect=0ms service=43ms status=200 bytes=3418 protocol=https
2022-11-09T22:50:37.645033+00:00 heroku[router]: at=info method=GET path="/assets/application-e0cf9d8fcb18bf7f909d8d91a5e78499f82ac29523d475bf3a9ab265d5e2b451.css" host=evening-refuge-08950.herokuapp.com request_id=1a6db3c5-21c9-467c-a1bb-bace228bacf1 fwd="13.110.54.11" dyno=web.1 connect=0ms service=2ms status=200 bytes=575 protocol=https
2022-11-09T22:50:37.651164+00:00 heroku[router]: at=info method=GET path="/assets/es-module-shims.min-d89e73202ec09dede55fb74115af9c5f9f2bb965433de1c2446e1faa6dac2470.js" host=evening-refuge-08950.herokuapp.com request_id=5ed3d951-5dd9-4ae6-9821-c48cc72104dc fwd="13.110.54.11" dyno=web.1 connect=0ms service=5ms status=200 bytes=11261 protocol=https
2022-11-09T22:50:37.780129+00:00 heroku[router]: at=info method=GET path="/assets/application-37f365cbecf1fa2810a8303f4b6571676fa1f9c56c248528bc14ddb857531b95.js" host=evening-refuge-08950.herokuapp.com request_id=8d833070-132d-4486-a285-7107ad6f85a3 fwd="13.110.54.11" dyno=web.1 connect=0ms service=3ms status=200 bytes=323 protocol=https
2022-11-09T22:50:37.843437+00:00 heroku[router]: at=info method=GET path="/assets/turbo.min-7ab2ea9f35bae4a4d65b552f9b93524099f267a8ba3a2e07002aaa7bff8ae4cf.js" host=evening-refuge-08950.herokuapp.com request_id=333eacfb-012b-4b13-8887-58b1218aaf73 fwd="13.110.54.11" dyno=web.1 connect=0ms service=4ms status=200 bytes=22015 protocol=https
2022-11-09T22:50:37.885918+00:00 heroku[router]: at=info method=GET path="/assets/stimulus-loading-1fc59770fb1654500044afd3f5f6d7d00800e5be36746d55b94a2963a7a228aa.js" host=evening-refuge-08950.herokuapp.com request_id=b639708d-c4c2-44c1-91ec-a98f8a88efab fwd="13.110.54.11" dyno=web.1 connect=0ms service=5ms status=200 bytes=1202 protocol=https
2022-11-09T22:50:37.888728+00:00 heroku[router]: at=info method=GET path="/assets/stimulus.min-2dae3fdcdb1a5ee8172d3dc02a2a10cd6d5f022cc7782b3888cedc06bab7388a.js" host=evening-refuge-08950.herokuapp.com request_id=b7449873-01cd-4c70-ae2e-1de9be977ca2 fwd="13.110.54.11" dyno=web.1 connect=0ms service=8ms status=200 bytes=9020 protocol=https
2022-11-09T22:50:37.916929+00:00 heroku[router]: at=info method=GET path="/assets/controllers/index-2db729dddcc5b979110e98de4b6720f83f91a123172e87281d5a58410fc43806.js" host=evening-refuge-08950.herokuapp.com request_id=37781631-3fea-4dc5-a196-f795335e8569 fwd="13.110.54.11" dyno=web.1 connect=0ms service=3ms status=200 bytes=444 protocol=https
2022-11-09T22:50:38.089306+00:00 heroku[router]: at=info method=GET path="/assets/controllers/application-368d98631bccbf2349e0d4f8269afb3fe9625118341966de054759d96ea86c7e.js" host=evening-refuge-08950.herokuapp.com request_id=19eea642-4409-4bb7-84d3-11ac4d66da7e fwd="13.110.54.11" dyno=web.1 connect=0ms service=4ms status=200 bytes=349 protocol=https
2022-11-09T22:50:38.231821+00:00 heroku[router]: at=info method=GET path="/assets/controllers/hello_controller-549135e8e7c683a538c3d6d517339ba470fcfb79d62f738a0a089ba41851a554.js" host=evening-refuge-08950.herokuapp.com request_id=dd18fc38-d73d-4325-8aef-cfc37d070089 fwd="13.110.54.11" dyno=web.1 connect=0ms service=2ms status=200 bytes=333 protocol=https
以下のように --tail
フラグオプションを使用してログコマンドを実行することで、完全なログストリームを入手することもできます。
$ heroku logs --tail
dyno のスリープおよびスケーリング
デフォルトでは、新しいアプリケーションは Eco dyno にデプロイされます。Eco アプリは、リソースを節約するために “スリープ” します。Eco dyno の動作について読むと、この動作の詳細がわかります。
dyno がスリープしないようにするには、「dyno タイプ」の記事で紹介されている Basic または Professional の dyno タイプにアップグレードできます。たとえば、アプリを Professional dyno に移行すると、Heroku に特定の数の dyno の実行を指示するコマンドを実行し、各 dyno で Web プロセスタイプを実行させて、アプリを簡単にスケールすることができます。
Rails コンソールの実行
Heroku では、heroku run
コマンドを使用して、One-off dyno (必要な場合にのみ実行するスクリプトおよびアプリケーション) でコマンドを実行できます。これを使用して、アプリの環境で試行するためにローカルターミナルにアタッチされた Rails コンソールプロセスを起動します。
$ heroku run rails console
irb(main):001:0> puts 1+1
2
デバッグに役立つもう 1 つのコマンドが $ heroku run bash
であり、新しい dyno を迅速に起動し、bash セッションにアクセスできるようにします。
Rake コマンドの実行
Rake は、コンソールと同様に、アタッチされたプロセスとして実行できます。
$ heroku run rake db:migrate
Web サーバーの設定
デフォルトで、アプリの Web プロセスでは、Rails 6 で Puma を使用する rails server
が実行されます。アプリをアップグレードする場合は、アプリケーション Gemfile
に puma
を追加する必要があります。
gem 'puma'
次に、以下を実行します。
$ bundle install
これで、アプリで Puma が使用されるように設定する準備が整いました。このチュートリアルでは、Rails 6 に付属するデフォルトの config/puma.rb
を使用しますが、Puma のドキュメントを読んで、パフォーマンスを最大限にするためのアプリケーションの設定について確認することをお勧めします。
最後に、アプリケーションディレクトリのルートで Procfile
を作成し、Rails の実行方法を Heroku に伝える必要があります。
Procfile の作成
Procfile を呼ばれるファイルを作成し、以下を入力して、Web プロセスを起動するのに使用するコマンドを変更します。
ファイル Procfile
で、以下のように記述します。
web: bundle exec puma -t 5:5 -p ${PORT:-3000} -e ${RACK_ENV:-development}
注意: このファイルは、正確に
Procfile
と命名する必要があります。
パフォーマンスを最大限にするために、Puma のドキュメントに基づいて設定ファイルを生成することをお勧めします。
Procfile をローカルで使用するには、heroku local
を使用できます。
Procfile
でコマンドを実行するだけでなく、heroku local
は、.env
ファイルを通じてローカルで環境変数を管理する場合にも役立ちます。ローカルの RACK_ENV
をご使用の環境での開発に設定し、接続先の PORT
を設定します。Heroku にプッシュする前に、Heroku アプリが実行される環境となる本番環境に設定された RACK_ENV
でテストする必要があります。
$ echo "RACK_ENV=development" >>.env
$ echo "PORT=3000" >> .env
注意:
.env
ファイルを使用してローカルで環境変数を使用するもう 1 つの代替方法が dotenv gem です。
さらに、ローカル環境の設定として、.env
を .gitignore
に追加する必要があります。
$ echo ".env" >> .gitignore
$ git add .gitignore
$ git commit -m "add .env to .gitignore"
Rails 6.0.0 を実行している場合、tmp/pids
ディレクトリを作成する必要があります。
$ mkdir -p tmp/pids
$ touch tmp/pids/.gitkeep
Foreman を使用して、Procfile をローカルでテストします。これで、以下を実行して Web サーバーを起動できます。
$ heroku local
[OKAY] Loaded ENV .env File as KEY=VALUE Format
2:50:42 PM web.1 | Puma starting in single mode...
2:50:42 PM web.1 | * Puma version: 5.6.5 (ruby 2.7.2-p137) ("Birdie's Version")
2:50:42 PM web.1 | * Min threads: 5
2:50:42 PM web.1 | * Max threads: 5
2:50:42 PM web.1 | * Environment: development
2:50:42 PM web.1 | * PID: 25472
2:50:43 PM web.1 | * Listening on http://0.0.0.0:3000
2:50:43 PM web.1 | Use Ctrl-C to stop
問題がなければ Ctrl+C
を押して終了し、変更を Heroku にデプロイできます。
$ git add .
$ git commit -m "use puma via procfile"
$ git push heroku main || git push heroku master
ps
を確認します。Web プロセスによって、Web サーバーとして Puma を指定している新しいコマンドが使用されていることが分かります。
$ heroku ps
Eco dyno hours quota remaining this month: 1000h 0m (100%)
Eco dyno usage for this app: 0h 0m (0%)
For more information on dyno sleeping and how to upgrade, see:
https://devcenter.heroku.com/articles/eco-dyno-hours#dyno-sleeping
=== web (Eco): bundle exec puma -t 5:5 -p ${PORT:-3000} -e ${RACK_ENV:-development} (1)
web.1: starting 2022/11/09 14:50:59 -0800 (~ 6s ago)
ログにも、Puma が使用されていることが反映されています。
$ heroku logs
Rails アセットパイプライン
Heroku へのデプロイ時に Rails アセットパイプラインを起動する方法は複数あります。アセットパイプラインに関する一般的な情報については、「Rails 3.1+ Asset Pipeline on Heroku Cedar」(Heroku Ceder での Rails 3.1 およびアセットパイプライン) の記事を参照してください。
config.assets.initialize_on_precompile
オプションは削除済みであり、Rails 6 では必要ありません。また、アセットコンパイルにおけるエラーはプッシュが失敗する原因となります。Rails 6 アセットパイプラインのサポートについては、Ruby サポートページを参照してください。
トラブルシューティング
プッシュしたアプリがクラッシュした (heroku ps
でステータス crashed
が表示された) 場合は、ログをチェックしてクラッシュの原因を見つけてください。一般的な問題には、たとえば以下があります。
開発/テスト gem でのランタイムの依存関係
デプロイ時に gem がない場合は、Bundler グループをチェックしてください。Heroku では、アプリは development
や test
グループなしで構築されます。アプリの実行がこれらのグループのいずれかからの gem に依存している場合、これをグループから除外します。
最もよくある例の 1 つとして、Rakefile
で Rspec タスクを使用する場合があります。Heroku のデプロイで以下が表示されます。
$ 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
そして、以下の問題が発生します。最初に、問題をローカルにコピーします。
$ 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 6 アプリケーションが Heroku にデプロイされました。次にお勧めするリソースを紹介します。
- 「Ruby サポートカテゴリ」では、Heroku での Ruby および Rails の使用に関する詳細を確認できます。
- 「デプロイカテゴリ」では、デプロイを効率的かつ簡単に行うことができるようにする、多くの強力な統合や機能を紹介しています。