Heroku スターターガイド (Rails 6.x)
この記事の英語版に更新があります。ご覧の翻訳には含まれていない変更点があるかもしれません。
Last updated 11 September 2020
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.0.2.1
1 gem installed
続いて新しいアプリを作成し、ルートディレクトリに移動します。
$ rails new myapp --database=postgresql
作成したら、アプリケーションのディレクトリに移動します。
$ cd myapp
ローカルでデータベースを作成します。
$ 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 that initialized the database.
#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 as a unix environment variable when you boot
# the app. Read https://guides.rubyonrails.org/configuring.html#configuring-a-database
# for a full rundown on how to provide these environment variables in a
# production deployment.
#
# On Heroku and other platform providers, you may have a full connection URL
# available as an environment variable. For example:
#
# DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase"
#
# You can use this database configuration with:
#
# production:
# url: <%= ENV['DATABASE_URL'] %>
#
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.2.0 以上が必要です。Heroku にはデフォルトで Ruby の最新バージョンがインストールされていますが、Gemfile
で ruby
DSL を使用して、特定のバージョンを指定できます。現在実行している Ruby のバージョンに応じて、次のように表示されます。
ruby "2.6.5"
同じ 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 master
nothing to commit, working tree clean
アプリケーションが Git にコミットされ、Heroku にデプロイできるようになりました。
Heroku へのアプリケーションのデプロイ
Rails アプリが含まれるディレクトリにいることを確認してから、Heroku でアプリを作成します。
$ heroku create
Creating app... done, radiant-sierra-11874
https://radiant-sierra-11874.herokuapp.com/ | https://git.heroku.com/radiant-sierra-11874.git
以下を実行して、リモートがプロジェクトに追加されていることを確認できます。
$ git config --list | grep heroku
remote.heroku.url=https://git.heroku.com/radiant-sierra-11874.git
remote.heroku.fetch=+refs/heads/*:refs/remotes/heroku/*
fatal: not in a git directory
が表示される場合は、ディレクトリが正しくない可能性があります。表示されなければ、コードをデプロイできます。コードをデプロイした後、データベースを移行する必要があります。データベースが適切にスケールされていることを確認し、問題はログを使用してすべてデバッグしてください。
コードをデプロイします。
$ git push heroku master
remote: Compressing source files... done.
remote: Building source:
remote:
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.0.2
remote: -----> Removing BUNDLED WITH version in the Gemfile.lock
remote: -----> Compiling Ruby/Rails
remote: -----> Using Ruby version: ruby-2.6.5
remote: -----> Installing dependencies using bundler 2.0.2
remote: Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4 --deployment
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.1
remote: Installing rake 13.0.1
remote: Fetching concurrent-ruby 1.1.6
remote: Fetching minitest 5.14.0
remote: Fetching thread_safe 0.3.6
remote: Installing thread_safe 0.3.6
remote: Installing minitest 5.14.0
remote: Installing concurrent-ruby 1.1.6
remote: Fetching zeitwerk 2.3.0
remote: Installing zeitwerk 2.3.0
remote: Fetching builder 3.2.4
remote: Installing builder 3.2.4
remote: Fetching erubi 1.9.0
remote: Installing erubi 1.9.0
remote: Fetching mini_portile2 2.4.0
remote: Installing mini_portile2 2.4.0
remote: Fetching crass 1.0.6
remote: Installing crass 1.0.6
remote: Fetching rack 2.2.2
remote: Fetching nio4r 2.5.2
remote: Installing rack 2.2.2
remote: Installing nio4r 2.5.2 with native extensions
remote: Fetching websocket-extensions 0.1.4
remote: Installing websocket-extensions 0.1.4
remote: Fetching mimemagic 0.3.4
remote: Fetching mini_mime 1.0.2
remote: Installing mimemagic 0.3.4
remote: Installing mini_mime 1.0.2
remote: Fetching msgpack 1.3.3
remote: Installing msgpack 1.3.3 with native extensions
remote: Using bundler 2.0.2
remote: Fetching ffi 1.12.2
remote: Installing ffi 1.12.2 with native extensions
remote: Fetching method_source 0.9.2
remote: Installing method_source 0.9.2
remote: Fetching pg 1.2.2
remote: Installing pg 1.2.2 with native extensions
remote: Fetching thor 1.0.1
remote: Installing thor 1.0.1
remote: Fetching tilt 2.0.10
remote: Installing tilt 2.0.10
remote: Fetching turbolinks-source 5.2.0
remote: Installing turbolinks-source 5.2.0
remote: Fetching tzinfo 1.2.6
remote: Installing tzinfo 1.2.6
remote: Fetching nokogiri 1.10.9
remote: Installing nokogiri 1.10.9 with native extensions
remote: Fetching i18n 1.8.2
remote: Installing i18n 1.8.2
remote: Fetching websocket-driver 0.7.1
remote: Installing websocket-driver 0.7.1 with native extensions
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.0
remote: Installing sprockets 4.0.0
remote: Fetching mail 2.7.1
remote: Installing mail 2.7.1
remote: Fetching marcel 0.3.3
remote: Installing marcel 0.3.3
remote: Fetching puma 4.3.3
remote: Installing puma 4.3.3 with native extensions
remote: Fetching bootsnap 1.4.6
remote: Installing bootsnap 1.4.6 with native extensions
remote: Fetching turbolinks 5.2.1
remote: Installing turbolinks 5.2.1
remote: Fetching sassc 2.2.1
remote: Installing sassc 2.2.1 with native extensions
remote: Fetching activesupport 6.0.2.1
remote: Installing activesupport 6.0.2.1
remote: Fetching loofah 2.4.0
remote: Installing loofah 2.4.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.0.2.1
remote: Installing activemodel 6.0.2.1
remote: Fetching jbuilder 2.10.0
remote: Installing jbuilder 2.10.0
remote: Fetching rails-html-sanitizer 1.3.0
remote: Fetching activejob 6.0.2.1
remote: Installing rails-html-sanitizer 1.3.0
remote: Installing activejob 6.0.2.1
remote: Fetching activerecord 6.0.2.1
remote: Installing activerecord 6.0.2.1
remote: Fetching actionview 6.0.2.1
remote: Installing actionview 6.0.2.1
remote: Fetching actionpack 6.0.2.1
remote: Installing actionpack 6.0.2.1
remote: Fetching actioncable 6.0.2.1
remote: Fetching activestorage 6.0.2.1
remote: Installing actioncable 6.0.2.1
remote: Installing activestorage 6.0.2.1
remote: Fetching actionmailer 6.0.2.1
remote: Installing actionmailer 6.0.2.1
remote: Fetching railties 6.0.2.1
remote: Fetching sprockets-rails 3.2.1
remote: Installing railties 6.0.2.1
remote: Installing sprockets-rails 3.2.1
remote: Fetching actionmailbox 6.0.2.1
remote: Installing actionmailbox 6.0.2.1
remote: Fetching actiontext 6.0.2.1
remote: Installing actiontext 6.0.2.1
remote: Fetching rails 6.0.2.1
remote: Fetching webpacker 4.2.2
remote: Installing rails 6.0.2.1
remote: Installing webpacker 4.2.2
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, 57 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:
remote: HEADS UP! i18n 1.1 changed fallbacks to exclude default locale.
remote: But that may break your application.
remote:
remote: If you are upgrading your Rails application from an older version of Rails:
remote:
remote: Please check your Rails app for 'config.i18n.fallbacks = true'.
remote: If you're using I18n (>= 1.1.0) and Rails (< 5.2.2), this should be
remote: 'config.i18n.fallbacks = [I18n.default_locale]'.
remote: If not, fallbacks will be broken in your app by I18n 1.1.x.
remote:
remote: If you are starting a NEW Rails application, you can ignore this notice.
remote:
remote: For more info see:
remote: https://github.com/svenfuchs/i18n/releases/tag/v1.1.0
remote:
remote: Bundle completed (200.01s)
remote: Cleaning up the bundler cache.
remote: -----> Installing node-v10.15.3-linux-x64
remote: -----> Installing yarn-v1.16.0
remote: -----> Detecting rake tasks
remote: -----> Preparing app for Rails asset pipeline
remote: Running: rake assets:precompile
remote: yarn install v1.16.0
remote: [1/4] Resolving packages...
remote: [2/4] Fetching packages...
remote: info fsevents@1.2.11: The platform "linux" is incompatible with this module.
remote: info "fsevents@1.2.11" is an optional dependency and failed compatibility check. Excluding it from installation.
remote: [3/4] Linking dependencies...
remote: warning " > webpack-dev-server@3.10.3" has unmet peer dependency "webpack@^4.0.0 || ^5.0.0".
remote: warning "webpack-dev-server > webpack-dev-middleware@3.7.2" has unmet peer dependency "webpack@^4.0.0".
remote: [4/4] Building fresh packages...
remote: Done in 22.90s.
remote: yarn install v1.16.0
remote: [1/4] Resolving packages...
remote: [2/4] Fetching packages...
remote: info fsevents@1.2.11: The platform "linux" is incompatible with this module.
remote: info "fsevents@1.2.11" is an optional dependency and failed compatibility check. Excluding it from installation.
remote: [3/4] Linking dependencies...
remote: warning " > webpack-dev-server@3.10.3" has unmet peer dependency "webpack@^4.0.0 || ^5.0.0".
remote: warning "webpack-dev-server > webpack-dev-middleware@3.7.2" has unmet peer dependency "webpack@^4.0.0".
remote: [4/4] Building fresh packages...
remote: Done in 4.99s.
remote: I, [2020-03-16T18:24:21.266413 #1702] INFO -- : Writing /tmp/build_ccf2067874b42c9999a2f517407160cf/public/assets/manifest-cadda289ef9c70eaa0879a36e6263cb33f7523a16b3ef862e0b8609cdc2bdab1.js
remote: I, [2020-03-16T18:24:21.266694 #1702] INFO -- : Writing /tmp/build_ccf2067874b42c9999a2f517407160cf/public/assets/manifest-cadda289ef9c70eaa0879a36e6263cb33f7523a16b3ef862e0b8609cdc2bdab1.js.gz
remote: I, [2020-03-16T18:24:21.266917 #1702] INFO -- : Writing /tmp/build_ccf2067874b42c9999a2f517407160cf/public/assets/application-d0ff5974b6aa52cf562bea5921840c032a860a91a3512f7fe8f768f6bbe005f6.css
remote: I, [2020-03-16T18:24:21.267071 #1702] INFO -- : Writing /tmp/build_ccf2067874b42c9999a2f517407160cf/public/assets/application-d0ff5974b6aa52cf562bea5921840c032a860a91a3512f7fe8f768f6bbe005f6.css.gz
remote: I, [2020-03-16T18:24:21.267392 #1702] INFO -- : Writing /tmp/build_ccf2067874b42c9999a2f517407160cf/public/assets/welcome-d0ff5974b6aa52cf562bea5921840c032a860a91a3512f7fe8f768f6bbe005f6.css
remote: I, [2020-03-16T18:24:21.267555 #1702] INFO -- : Writing /tmp/build_ccf2067874b42c9999a2f517407160cf/public/assets/welcome-d0ff5974b6aa52cf562bea5921840c032a860a91a3512f7fe8f768f6bbe005f6.css.gz
remote: Compiling...
remote: Compiled all packs in /tmp/build_ccf2067874b42c9999a2f517407160cf/public/packs
remote: Hash: 43ea45064c6e4163e480
remote: Version: webpack 4.42.0
remote: Time: 6404ms
remote: Built at: 03/16/2020 6:24:29 PM
remote: Asset Size Chunks Chunk Names
remote: js/application-e3bcdbe127e485b2e4b4.js 69.2 KiB 0 [emitted] [immutable] application
remote: js/application-e3bcdbe127e485b2e4b4.js.gz 17.7 KiB [emitted]
remote: js/application-e3bcdbe127e485b2e4b4.js.map 205 KiB 0 [emitted] [dev] application
remote: js/application-e3bcdbe127e485b2e4b4.js.map.gz 51 KiB [emitted]
remote: manifest.json 364 bytes [emitted]
remote: manifest.json.gz 142 bytes [emitted]
remote: Entrypoint application = js/application-e3bcdbe127e485b2e4b4.js js/application-e3bcdbe127e485b2e4b4.js.map
remote: [0] (webpack)/buildin/module.js 552 bytes {0} [built]
remote: [1] ./app/javascript/packs/application.js 742 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 (38.74s)
remote: Cleaning assets
remote: Running: rake assets:clean
remote: -----> Detecting rails configuration
remote:
remote: ###### WARNING:
remote:
remote: You set your `config.active_storage.service` to :local in production.
remote: If you are uploading files to this app, they will not persist after the app
remote: is restarted, on one-off dynos, or if the app has multiple dynos.
remote: Heroku applications have an ephemeral file system. To
remote: persist uploaded files, please use a service such as S3 and update your Rails
remote: configuration.
remote:
remote: For more information can be found in this article:
remote: https://devcenter.heroku.com/articles/active-storage-on-heroku
remote:
remote:
remote:
remote: ###### WARNING:
remote:
remote: We detected that some binary dependencies required to
remote: use all the preview features of Active Storage are not
remote: present on this system.
remote:
remote: For more information please see:
remote: https://devcenter.heroku.com/articles/active-storage-on-heroku
remote:
remote:
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:
remote: -----> Discovering process types
remote: Procfile declares types -> (none)
remote: Default types for buildpack -> console, rake, web
remote:
remote: -----> Compressing...
remote: Done: 87.9M
remote: -----> Launching...
remote: Released v6
remote: https://radiant-sierra-11874.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/radiant-sierra-11874.git
* [new branch] master -> master
出力に警告やエラーがないかどうかを必ず確認してください。何も問題がなければ、データベースを移行できます。
データベースの移行
アプリケーションでデータベースを使用している場合は、以下を実行して手動でデータベースを移行する必要があります。
$ 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: 998h 53m (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 -e $RAILS_ENV (1)
web.1: starting 2020/03/16 13:24:45 -0500 (~ 12s ago)
ここでは、1 つの dyno が実行中です。
heroku open
を使用して、ブラウザでアプリにアクセスできます。
$ heroku open
すると、先ほど挿入したテキスト「Hello World」が表示されます。
Heroku では、開発中の複雑さをなくすため、デフォルトの URL が提供されます。スケールアップして Heroku を本番環境で使用する準備が整っている場合は、独自のカスタムドメインを追加できます。
ログの表示
アプリが適切に機能しないような問題が発生した場合は、ログをチェックする必要があります。
ログコマンドの 1 つである heroku logs
を使って、実行中のアプリに関する情報を表示できます。
$ heroku logs
2020-03-16T18:20:19.382662+00:00 app[api]: Initial release by user developer@example.com2020-03-16T18:20:19.382662+00:00 app[api]: Release v1 created by user developer@example.com2020-03-16T18:20:19.562818+00:00 app[api]: Release v2 created by user developer@example.com2020-03-16T18:20:19.562818+00:00 app[api]: Enable Logplex by user developer@example.com2020-03-16T18:20:24.000000+00:00 app[api]: Build started by user developer@example.com2020-03-16T18:24:43.899544+00:00 app[api]: Release v3 created by user developer@example.com2020-03-16T18:24:43.899544+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.com2020-03-16T18:24:45.109440+00:00 app[api]: Release v5 created by user developer@example.com2020-03-16T18:24:45.088747+00:00 app[api]: Running release v4 commands by user developer@example.com2020-03-16T18:24:45.088747+00:00 app[api]: Attach DATABASE (@ref:postgresql-triangular-59209) by user developer@example.com2020-03-16T18:24:45.109440+00:00 app[api]: @ref:postgresql-triangular-59209 completed provisioning, setting DATABASE_URL. by user developer@example.com2020-03-16T18:24:45.544442+00:00 app[api]: Scaled to console@0:Free rake@0:Free web@1:Free by user developer@example.com2020-03-16T18:24:45.519682+00:00 app[api]: Release v6 created by user developer@example.com2020-03-16T18:24:45.519682+00:00 app[api]: Deploy cfe2514d by user developer@example.com2020-03-16T18:24:50.000000+00:00 app[api]: Build succeeded
2020-03-16T18:24:54.527896+00:00 heroku[web.1]: Starting process with command `bin/rails server -p 11504 -e production`
2020-03-16T18:25:01.439054+00:00 app[web.1]: => Booting Puma
2020-03-16T18:25:01.439119+00:00 app[web.1]: => Rails 6.0.2.1 application starting in production
2020-03-16T18:25:01.439120+00:00 app[web.1]: => Run `rails server --help` for more startup options
2020-03-16T18:25:03.202568+00:00 app[web.1]: Puma starting in single mode...
2020-03-16T18:25:03.202619+00:00 app[web.1]: * Version 4.3.3 (ruby 2.6.5-p114), codename: Mysterious Traveller
2020-03-16T18:25:03.202620+00:00 app[web.1]: * Min threads: 5, max threads: 5
2020-03-16T18:25:03.202621+00:00 app[web.1]: * Environment: production
2020-03-16T18:25:03.203798+00:00 app[web.1]: * Listening on tcp://0.0.0.0:11504
2020-03-16T18:25:03.204170+00:00 app[web.1]: Use Ctrl-C to stop
以下のように --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
1:25:08 PM web.1 | Puma starting in single mode...
1:25:08 PM web.1 | * Version 4.3.3 (ruby 2.6.5-p114), codename: Mysterious Traveller
1:25:08 PM web.1 | * Min threads: 5, max threads: 5
1:25:08 PM web.1 | * Environment: development
1:25:11 PM web.1 | * Listening on tcp://0.0.0.0:3000
1:25:11 PM web.1 | Use Ctrl-C to stop
問題がなければ Ctrl+C
を押して終了し、変更を Heroku にデプロイできます。
$ git add .
$ git commit -m "use puma via procfile"
$ git push heroku master
ps
を確認します。Web プロセスによって、Web サーバーとして Puma を指定している新しいコマンドが使用されていることが分かります。
$ heroku ps
Free dyno hours quota remaining this month: 998h 53m (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 2020/03/16 13:26:17 -0500 (~ 9s 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 の使用に関する詳細を確認できます。
- 「デプロイカテゴリ」では、デプロイを効率的かつ簡単に行うことができるようにする、多くの強力な統合や機能を紹介しています。