Heroku スターターガイド (Rails 6.x)
この記事の英語版に更新があります。ご覧の翻訳には含まれていない変更点があるかもしれません。
最終更新日 2022年01月03日(月)
Table of Contents
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 ユーザーアカウント: 無料ですぐにサインアップできます。
ローカルの設定
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 --no-document
Successfully installed rails-6.1.1
1 gem installed
続いて新しいアプリを作成し、ルートディレクトリに移動します。
$ rails 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 ./Gemfile.lock
ローカルでデータベースを作成します。
$ bin/rails db:create
Database 'myapp_development' already exists
Database 'myapp_test' 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>]
<command> [<args>]
出力がない、または command not found
が出力される場合は、Git をシステムにインストールする必要があります。
Git が機能することを検証した後、$ ls
を実行して Rails アプリのディレクトリにいることを確認してください。
出力は以下のようになります。
$ ls
Gemfile
Gemfile-e
Gemfile.lock
README.md
Rakefile
app
babel.config.js
bin
config
config.ru
db
lib
log
node_modules
package.json
postcss.config.js
public
storage
test
tmp
vendor
yarn.lock
次に、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
Creating app... done, aqueous-sierra-44713
https://aqueous-sierra-44713.herokuapp.com/ | https://git.heroku.com/aqueous-sierra-44713.git
以下を実行して、リモートがプロジェクトに追加されていることを確認できます。
$ git config --list --local | grep heroku
remote.heroku.url=https://git.heroku.com/aqueous-sierra-44713.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
Free dyno hours quota remaining this month: 999h 7m (99%)
Free dyno usage for this app: 0h 0m (0%)
For more information on dyno sleeping and how to upgrade, see:
https://devcenter.heroku.com/articles/dyno-sleeping
=== web (Free): bin/rails server -p ${PORT:-5000} -e $RAILS_ENV (1)
web.1: up 2021/02/08 15:39:37 -0600 (~ 1s ago)
ここでは、1 つの dyno が実行中です。
heroku open
を使用して、ブラウザでアプリにアクセスできます。
$ heroku open
すると、先ほど挿入したテキスト「Hello World」が表示されます。
Heroku では、開発中の複雑さをなくすため、デフォルトの URL が提供されます。スケールアップして Heroku を本番環境で使用する準備が整っている場合は、独自のカスタムドメインを追加できます。
ログの表示
アプリが適切に機能しないような問題が発生した場合は、ログをチェックする必要があります。
ログコマンドの 1 つである heroku logs
を使って、実行中のアプリに関する情報を表示できます。
$ heroku logs
2021-02-08T21:33:57.056624+00:00 app[api]: Initial release by user developer@example.com2021-02-08T21:33:57.056624+00:00 app[api]: Release v1 created by user developer@example.com2021-02-08T21:33:57.235552+00:00 app[api]: Enable Logplex by user developer@example.com2021-02-08T21:33:57.235552+00:00 app[api]: Release v2 created by user developer@example.com2021-02-08T21:34:03.000000+00:00 app[api]: Build started by user developer@example.com2021-02-08T21:39:20.880108+00:00 app[api]: Release v3 created by user developer@example.com2021-02-08T21:39:20.880108+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.com2021-02-08T21:39:21.649264+00:00 app[api]: Attach DATABASE (@ref:postgresql-horizontal-25587) by user developer@example.com2021-02-08T21:39:21.649264+00:00 app[api]: Running release v4 commands by user developer@example.com2021-02-08T21:39:21.663439+00:00 app[api]: Release v5 created by user developer@example.com2021-02-08T21:39:21.663439+00:00 app[api]: @ref:postgresql-horizontal-25587 completed provisioning, setting DATABASE_URL. by user developer@example.com2021-02-08T21:39:22.003297+00:00 app[api]: Deploy 4b652842 by user developer@example.com2021-02-08T21:39:22.003297+00:00 app[api]: Release v6 created by user developer@example.com2021-02-08T21:39:22.020451+00:00 app[api]: Scaled to console@0:Free rake@0:Free web@1:Free by user developer@example.com2021-02-08T21:39:30.000000+00:00 app[api]: Build succeeded
2021-02-08T21:39:30.655276+00:00 heroku[web.1]: Starting process with command `bin/rails server -p ${PORT:-5000} -e production`
2021-02-08T21:39:36.096396+00:00 app[web.1]: => Booting Puma
2021-02-08T21:39:36.096416+00:00 app[web.1]: => Rails 6.1.1 application starting in production
2021-02-08T21:39:36.096417+00:00 app[web.1]: => Run `bin/rails server --help` for more startup options
2021-02-08T21:39:37.746693+00:00 app[web.1]: Puma starting in single mode...
2021-02-08T21:39:37.746740+00:00 app[web.1]: * Puma version: 5.2.1 (ruby 2.7.2-p137) ("Fettisdagsbulle")
2021-02-08T21:39:37.746741+00:00 app[web.1]: * Min threads: 5
2021-02-08T21:39:37.746741+00:00 app[web.1]: * Max threads: 5
2021-02-08T21:39:37.746748+00:00 app[web.1]: * Environment: production
2021-02-08T21:39:37.746748+00:00 app[web.1]: * PID: 4
2021-02-08T21:39:37.747064+00:00 app[web.1]: * Listening on http://0.0.0.0:41726
2021-02-08T21:39:37.759254+00:00 app[web.1]: Use Ctrl-C to stop
2021-02-08T21:39:37.982361+00:00 heroku[web.1]: State changed from starting to up
2021-02-08T21:39:44.980825+00:00 heroku[router]: at=info method=GET path="/" host=aqueous-sierra-44713.herokuapp.com request_id=f040a57c-2b15-40f8-b9c1-88e573c2607a fwd="13.110.54.42" dyno=web.1 connect=1ms service=32ms status=200 bytes=1846 protocol=https
2021-02-08T21:39:45.095632+00:00 heroku[router]: at=info method=GET path="/assets/application-04024382391bb910584145d8113cf35ef376b55d125bb4516cebeb14ce788597.css" host=aqueous-sierra-44713.herokuapp.com request_id=36395e8d-47f3-46ea-a995-9ca7795660eb fwd="13.110.54.42" dyno=web.1 connect=1ms service=3ms status=200 bytes=195 protocol=https
2021-02-08T21:39:45.188246+00:00 heroku[router]: at=info method=GET path="/packs/js/application-2d24cb02e79dc1ee88b7.js" host=aqueous-sierra-44713.herokuapp.com request_id=62364ff3-5b48-4af2-8532-125171d25568 fwd="13.110.54.42" dyno=web.1 connect=1ms service=3ms status=200 bytes=15905 protocol=https
2021-02-08T21:39:45.290044+00:00 heroku[router]: at=info method=GET path="/packs/js/application-2d24cb02e79dc1ee88b7.js" host=aqueous-sierra-44713.herokuapp.com request_id=33882e49-8d6a-4af5-ad92-5acd51260489 fwd="13.110.54.42" dyno=web.1 connect=0ms service=2ms status=200 bytes=15905 protocol=https
2021-02-08T21:39:45.487187+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=aqueous-sierra-44713.herokuapp.com request_id=df1fb11d-6f75-49c3-a1ad-4aad45a2e872 fwd="13.110.54.42" dyno=web.1 connect=1ms service=3ms status=200 bytes=143 protocol=https
以下のように --tail
フラグオプションを使用してログコマンドを実行することで、完全なログストリームを入手することもできます。
$ heroku logs --tail
dyno のスリープおよびスケーリング
デフォルトでは、新しいアプリケーションは Free dyno にデプロイされます。無料のアプリはリソースを節約するために “スリープ” します。Free dyno の動作について読むと、この動作の詳細がわかります。
dyno がスリープしないようにするには、「dyno タイプ」の記事で紹介されている Hobby または 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
3:39:52 PM web.1 | Puma starting in single mode...
3:39:52 PM web.1 | * Puma version: 5.2.1 (ruby 2.7.2-p137) ("Fettisdagsbulle")
3:39:52 PM web.1 | * Min threads: 5
3:39:52 PM web.1 | * Max threads: 5
3:39:52 PM web.1 | * Environment: development
3:39:52 PM web.1 | * PID: 21163
3:39:53 PM web.1 | * Listening on http://0.0.0.0:3000
3:39:53 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
Free dyno hours quota remaining this month: 999h 7m (99%)
Free dyno usage for this app: 0h 0m (0%)
For more information on dyno sleeping and how to upgrade, see:
https://devcenter.heroku.com/articles/dyno-sleeping
=== web (Free): bundle exec puma -t 5:5 -p ${PORT:-3000} -e ${RACK_ENV:-development} (1)
web.1: starting 2021/02/08 15:41:04 -0600 (~ 13s 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 の使用に関する詳細を確認できます。
- 「デプロイカテゴリ」では、デプロイを効率的かつ簡単に行うことができるようにする、多くの強力な統合や機能を紹介しています。
- Heroku の開発者としての体験および CI/CD 機能についての詳細は、「Heroku Enterprise Developer Learning Journey」を参照してください。