Skip Navigation
Show nav
Heroku Dev Center
  • Get Started
  • ドキュメント
  • Changelog
  • Search
  • Get Started
    • Node.js
    • Ruby on Rails
    • Ruby
    • Python
    • Java
    • PHP
    • Go
    • Scala
    • Clojure
  • ドキュメント
  • Changelog
  • More
    Additional Resources
    • Home
    • Elements
    • Products
    • Pricing
    • Careers
    • Help
    • Status
    • Events
    • Podcasts
    • Compliance Center
    Heroku Blog

    Heroku Blog

    Find out what's new with Heroku on our blog.

    Visit Blog
  • Log inorSign up
View categories

Categories

  • Heroku のアーキテクチャ
    • Dyno (アプリコンテナ)
    • スタック (オペレーティングシステムイメージ)
    • ネットワーキングと DNS
    • プラットフォームポリシー
    • プラットフォームの原則
  • コマンドライン
  • デプロイ
    • Git を使用したデプロイ
    • Docker によるデプロイ
    • デプロイ統合
  • 継続的デリバリー
    • 継続的統合
  • 言語サポート
    • Node.js
    • Ruby
      • Bundler の使用
      • Rails のサポート
    • Python
      • Python でのバックグランドジョブ
      • Django の使用
    • Java
      • Maven の使用
      • Java でのデータベース操作
      • Play Framework の使用
      • Spring Boot の使用
      • Java の高度なトピック
    • PHP
    • Go
      • Go の依存関係管理
    • Scala
    • Clojure
  • データベースとデータ管理
    • Heroku Postgres
      • Postgres の基礎
      • Postgres Getting Started
      • Postgres のパフォーマンス
      • Postgres のデータ転送と保持
      • Postgres の可用性
      • Postgres の特別なトピック
    • Heroku Redis
    • Apache Kafka on Heroku
    • その他のデータストア
  • モニタリングとメトリクス
    • ログ記録
  • アプリのパフォーマンス
  • アドオン
    • すべてのアドオン
  • 共同作業
  • セキュリティ
    • アプリのセキュリティ
    • ID と認証
    • コンプライアンス
  • Heroku Enterprise
    • Private Space
      • インフラストラクチャネットワーキング
    • Enterprise Accounts
    • Enterprise Team
    • Heroku Connect (Salesforce 同期)
      • Heroku Connect の管理
      • Heroku Connect のリファレンス
      • Heroku Connect のトラブルシューティング
    • シングルサインオン (SSO)
  • パターンとベストプラクティス
  • Heroku の拡張
    • Platform API
    • アプリの Webhook
    • Heroku Labs
    • アドオンのビルド
      • アドオン開発のタスク
      • アドオン API
      • アドオンのガイドラインと要件
    • CLI プラグインのビルド
    • 開発ビルドパック
    • Dev Center
  • アカウントと請求
  • トラブルシューティングとサポート
  • Integrating with Salesforce
  • 言語サポート
  • Ruby
  • Rails のサポート
  • Heroku スターターガイド (Rails 5.x)

Heroku スターターガイド (Rails 5.x)

日本語 — Switch to English

この記事の英語版に更新があります。ご覧の翻訳には含まれていない変更点があるかもしれません。

最終更新日 2022年11月17日(木)

Table of Contents

  • ローカルの設定
  • 新しい Rails アプリの作成 (または既存の Rails アプリのアップグレード)
  • pg gem の追加
  • ウェルカムページの作成
  • Heroku gem
  • Ruby バージョンの指定
  • Git でのアプリの保存
  • Heroku へのアプリケーションのデプロイ
  • データベースの移行
  • アプリケーションへのアクセス
  • ログの表示
  • dyno のスリープおよびスケーリング
  • Rails コンソールの実行
  • Rake コマンドの実行
  • Web サーバーの設定
  • Rails アセットパイプライン
  • トラブルシューティング
  • 次のステップ

2022 年 11 月 28 日以降、Heroku dyno、Heroku Postgres、および Heroku Data for Redis® の無料プランは使用できません。 これらのリソースのいずれかを使用しているアプリがある場合は、アプリを引き続き実行してデータを保持できるよう、この日までに有料プランにアップグレード​する必要があります。資格のある学生の皆様は、新しい Heroku for GitHub Students プログラム​を通じてプラットフォームクレジットを申請できます。詳細は、ブログ​と FAQ​ を参照してください。

Rails の利用可能な最新バージョンは Rails 7​ です。新しいアプリケーションを開始する場合は、最新リリースバージョンを使用することをお勧めします。

Ruby on Rails は、Ruby​ で記述され、広く使われている Web フレームワークです。このガイドでは、Heroku での Rails 5 の使用について説明します。Heroku での Rails 旧バージョンの実行の詳細については、Rails 4.x​ または Rails 3.x​ に関するチュートリアルを参照してください。

このガイドでは、以下が必要となります。

  • Ruby/Rails および Git の基本的な知識
  • Ruby 2.2.0+、Rubygems、Bundler、Rails 5 のローカルにインストールされたバージョン+
  • 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 を使用する既存のアプリから開始する場合は、続行する前に、Rails 5 にアップグレード​してください。既存のアプリから開始しない場合は、vanilla Rails 5 アプリがサンプルアプリとして役立ちます。

新しいアプリを作成するには、最初に、rails -v​ を実行して、Rails 5.x を使用していることを確認してください。必要に応じて、Rails の新しいバージョンは、以下を実行すると取得できます。

$ gem install rails -v 5.2.2 --no-document
Successfully installed rails-5.2.2
1 gem installed

続いて新しいアプリを作成し、ルートディレクトリに移動します。

$ rails _5.2.2_ 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​」(Heroke で Sqlite3 を使用できない理由) を参照してください。

pg​ gem の使用に加えて、config/database.yml​ ファイルで postgresql​ アダプターが使用されていることも確認します。config/database.yml​ ファイルの開発セクションの外観は次のようになります。

$ cat config/database.yml
# PostgreSQL. Versions 9.1 and up are supported.
#
# Install the pg driver:
#   gem install pg
# On OS X with Homebrew:
#   gem install pg -- --with-pg-config=/usr/local/bin/pg_config
# On OS X 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
  # http://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/secrets.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 http://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 5 の本番環境には、デフォルトで静的なインデックスページがありません。新しいアプリを使用するとき、本番環境にはルートページがないため、ルートページを作成する必要があります。最初に、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 5 では、Ruby 2.2.0 以上が必要です。Heroku にはデフォルトで Ruby の最新バージョンがインストールされていますが、Gemfile​ で ruby​ DSL を使用して、特定のバージョンを指定することができます。現在実行している Ruby のバージョンに応じて、次のように表示されます。

ruby "2.6.0"

同じ 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
bin
config
config.ru
db
lib
log
package.json
public
storage
test
tmp
vendor

次に、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, secret-tor-42278
https://secret-tor-42278.herokuapp.com/ | https://git.heroku.com/secret-tor-42278.git

以下を実行して、リモートがプロジェクトに追加されていることを確認できます。

$ git config --list | grep heroku
remote.heroku.url=https://git.heroku.com/secret-tor-42278.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: -----> Compiling Ruby/Rails
remote: -----> Using Ruby version: ruby-2.6.0
remote: -----> Installing dependencies using bundler 1.15.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 12.3.2
remote:        Installing rake 12.3.2
remote:        Fetching concurrent-ruby 1.1.4
remote:        Fetching thread_safe 0.3.6
remote:        Fetching minitest 5.11.3
remote:        Installing thread_safe 0.3.6
remote:        Installing minitest 5.11.3
remote:        Installing concurrent-ruby 1.1.4
remote:        Fetching builder 3.2.3
remote:        Installing builder 3.2.3
remote:        Fetching erubi 1.8.0
remote:        Installing erubi 1.8.0
remote:        Fetching mini_portile2 2.4.0
remote:        Fetching crass 1.0.4
remote:        Installing mini_portile2 2.4.0
remote:        Fetching rack 2.0.6
remote:        Installing crass 1.0.4
remote:        Installing rack 2.0.6
remote:        Fetching nio4r 2.3.1
remote:        Installing nio4r 2.3.1 with native extensions
remote:        Fetching websocket-extensions 0.1.3
remote:        Installing websocket-extensions 0.1.3
remote:        Fetching mini_mime 1.0.1
remote:        Installing mini_mime 1.0.1
remote:        Fetching arel 9.0.0
remote:        Installing arel 9.0.0
remote:        Fetching mimemagic 0.3.3
remote:        Fetching msgpack 1.2.4
remote:        Installing msgpack 1.2.4 with native extensions
remote:        Installing mimemagic 0.3.3
remote:        Using bundler 1.17.2
remote:        Fetching coffee-script-source 1.12.2
remote:        Installing coffee-script-source 1.12.2
remote:        Fetching execjs 2.7.0
remote:        Installing execjs 2.7.0
remote:        Fetching method_source 0.9.2
remote:        Installing method_source 0.9.2
remote:        Fetching thor 0.20.3
remote:        Installing thor 0.20.3
remote:        Fetching ffi 1.9.25
remote:        Installing ffi 1.9.25 with native extensions
remote:        Fetching multi_json 1.13.1
remote:        Installing multi_json 1.13.1
remote:        Fetching pg 1.1.3
remote:        Installing pg 1.1.3 with native extensions
remote:        Fetching puma 3.12.0
remote:        Installing puma 3.12.0 with native extensions
remote:        Fetching rb-fsevent 0.10.3
remote:        Installing rb-fsevent 0.10.3
remote:        Fetching tilt 2.0.9
remote:        Installing tilt 2.0.9
remote:        Fetching turbolinks-source 5.2.0
remote:        Installing turbolinks-source 5.2.0
remote:        Fetching tzinfo 1.2.5
remote:        Installing tzinfo 1.2.5
remote:        Fetching nokogiri 1.9.1
remote:        Installing nokogiri 1.9.1 with native extensions
remote:        Fetching i18n 1.4.0
remote:        Installing i18n 1.4.0
remote:        Fetching websocket-driver 0.7.0
remote:        Installing websocket-driver 0.7.0 with native extensions
remote:        Fetching mail 2.7.1
remote:        Installing mail 2.7.1
remote:        Fetching rack-test 1.1.0
remote:        Installing rack-test 1.1.0
remote:        Fetching sprockets 3.7.2
remote:        Installing sprockets 3.7.2
remote:        Fetching marcel 0.3.3
remote:        Installing marcel 0.3.3
remote:        Fetching coffee-script 2.4.1
remote:        Installing coffee-script 2.4.1
remote:        Fetching uglifier 4.1.20
remote:        Installing uglifier 4.1.20
remote:        Fetching bootsnap 1.3.2
remote:        Installing bootsnap 1.3.2 with native extensions
remote:        Fetching rb-inotify 0.10.0
remote:        Installing rb-inotify 0.10.0
remote:        Fetching turbolinks 5.2.0
remote:        Installing turbolinks 5.2.0
remote:        Fetching activesupport 5.2.2
remote:        Installing activesupport 5.2.2
remote:        Fetching loofah 2.2.3
remote:        Fetching sass-listen 4.0.0
remote:        Installing loofah 2.2.3
remote:        Installing sass-listen 4.0.0
remote:        Fetching rails-dom-testing 2.0.3
remote:        Installing rails-dom-testing 2.0.3
remote:        Fetching globalid 0.4.1
remote:        Installing globalid 0.4.1
remote:        Fetching activemodel 5.2.2
remote:        Installing activemodel 5.2.2
remote:        Fetching jbuilder 2.8.0
remote:        Installing jbuilder 2.8.0
remote:        Fetching sass 3.7.2
remote:        Installing sass 3.7.2
remote:        Fetching rails-html-sanitizer 1.0.4
remote:        Installing rails-html-sanitizer 1.0.4
remote:        Fetching activejob 5.2.2
remote:        Installing activejob 5.2.2
remote:        Fetching activerecord 5.2.2
remote:        Fetching actionview 5.2.2
remote:        Installing activerecord 5.2.2
remote:        Installing actionview 5.2.2
remote:        Fetching actionpack 5.2.2
remote:        Installing actionpack 5.2.2
remote:        Fetching actioncable 5.2.2
remote:        Fetching activestorage 5.2.2
remote:        Fetching actionmailer 5.2.2
remote:        Installing actioncable 5.2.2
remote:        Installing actionmailer 5.2.2
remote:        Installing activestorage 5.2.2
remote:        Fetching railties 5.2.2
remote:        Installing railties 5.2.2
remote:        Fetching sprockets-rails 3.2.1
remote:        Installing sprockets-rails 3.2.1
remote:        Fetching coffee-rails 4.2.2
remote:        Fetching sass-rails 5.0.7
remote:        Fetching rails 5.2.2
remote:        Installing rails 5.2.2
remote:        Installing coffee-rails 4.2.2
remote:        Installing sass-rails 5.0.7
remote:        Bundle complete! 18 Gemfile dependencies, 61 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:        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:        For more info see:
remote:        https://github.com/svenfuchs/i18n/releases/tag/v1.1.0
remote:
remote:        Post-install message from sass:
remote:
remote:        Ruby Sass is deprecated and will be unmaintained as of 26 March 2019.
remote:
remote:        * If you use Sass as a command-line tool, we recommend using Dart Sass, the new
remote:          primary implementation: https://sass-lang.com/install
remote:
remote:        * If you use Sass as a plug-in for a Ruby web framework, we recommend using the
remote:          sassc gem: https://github.com/sass/sassc-ruby#readme
remote:
remote:        * For more details, please refer to the Sass blog:
remote:          http://sass.logdown.com/posts/7081811
remote:
remote:        Removing bundler (1.15.2)
remote:        Bundle completed (42.62s)
remote:        Cleaning up the bundler cache.
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: -----> Installing node-v8.10.0-linux-x64
remote: -----> Detecting rake tasks
remote: -----> Preparing app for Rails asset pipeline
remote:        Running: rake assets:precompile
remote:        Yarn executable was not detected in the system.
remote:        Download Yarn at https://yarnpkg.com/en/docs/install
remote:        I, [2019-01-03T17:16:39.683335 #1309]  INFO -- : Writing /tmp/build_020cb65e00979312f798ba48446f2064/public/assets/application-9622f0fe63bfad91bdeaa3a771e86262263840678fd66849b311b6cfb3f7cc85.js
remote:        I, [2019-01-03T17:16:39.683750 #1309]  INFO -- : Writing /tmp/build_020cb65e00979312f798ba48446f2064/public/assets/application-9622f0fe63bfad91bdeaa3a771e86262263840678fd66849b311b6cfb3f7cc85.js.gz
remote:        I, [2019-01-03T17:16:39.693392 #1309]  INFO -- : Writing /tmp/build_020cb65e00979312f798ba48446f2064/public/assets/application-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css
remote:        I, [2019-01-03T17:16:39.693515 #1309]  INFO -- : Writing /tmp/build_020cb65e00979312f798ba48446f2064/public/assets/application-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css.gz
remote:        Asset precompilation completed (3.72s)
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: ###### 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: ###### 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: 41.3M
remote: -----> Launching...
remote:        Released v6
remote:        https://secret-tor-42278.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/secret-tor-42278.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: 967h 44m (96%)
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 2019/01/03 11:16:50 -0600 (~ 6s ago)

ここでは、1 つの dyno が実行中です。

heroku open​ を使用して、ブラウザでアプリにアクセスできます。

$ heroku open

すると、先ほど挿入したテキスト「Hello World」が表示されます。

Heroku では、開発中の複雑さをなくすため、デフォルトの URL が提供されます。スケールアップして Heroku を本番環境で使用する準備が整っている場合は、独自のカスタムドメイン​を追加できます。

ログの表示

アプリが適切に機能しないような問題が発生した場合は、ログをチェックする必要があります。

ログコマンド​の 1 つである heroku logs​ を使って、実行中のアプリに関する情報を表示できます。

$ heroku logs
2019-01-03T17:15:46.454068+00:00 app[api]: Enable Logplex by user developer@example.com2019-01-03T17:15:46.277667+00:00 app[api]: Initial release by user developer@example.com2019-01-03T17:15:46.454068+00:00 app[api]: Release v2 created by user developer@example.com2019-01-03T17:15:48.000000+00:00 app[api]: Build started by user developer@example.com2019-01-03T17:16:49.295117+00:00 app[api]: Release v3 created by user developer@example.com2019-01-03T17:16:49.295117+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.com2019-01-03T17:16:50.054946+00:00 app[api]: Running release v4 commands by user developer@example.com2019-01-03T17:16:50.490534+00:00 app[api]: Scaled to console@0:Free rake@0:Free web@1:Free by user developer@example.com2019-01-03T17:16:50.075764+00:00 app[api]: Release v5 created by user developer@example.com2019-01-03T17:16:50.075764+00:00 app[api]: @ref:postgresql-colorful-78926 completed provisioning, setting DATABASE_URL. by user developer@example.com2019-01-03T17:16:53.668660+00:00 heroku[web.1]: Starting process with command `bin/rails server -p 21857 -e production`
2019-01-03T17:16:53.000000+00:00 app[api]: Build succeeded
2019-01-03T17:16:59.442990+00:00 heroku[web.1]: State changed from starting to up

以下のように --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 5 で Puma を使用する rails server​ が実行されます。アプリをアップグレードする場合は、アプリケーション Gemfile​ に puma​ を追加する必要があります。

gem 'puma'

次に、以下を実行します。

$ bundle install

これで、アプリで Puma が使用されるように設定する準備が整いました。このチュートリアルでは、Rails 5 に付属するデフォルトの 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"

Foreman を使用して、Procfile をローカルでテストします。これで、以下を実行して Web サーバーを起動できます。

$ heroku local
[OKAY] Loaded ENV .env File as KEY=VALUE Format
11:17:03 AM web.1 |  Puma starting in single mode...
11:17:03 AM web.1 |  * Version 3.12.0 (ruby 2.6.0-p-1), codename: Llamas in Pajamas
11:17:03 AM web.1 |  * Min threads: 5, max threads: 5
11:17:03 AM web.1 |  * Environment: development
11:17:04 AM web.1 |  * Listening on tcp://0.0.0.0:3000
11:17:04 AM 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: 967h 44m (96%)
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 2019/01/03 11:17:26 -0600 (~ 5s 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 5 では必要ありません。また、アセットコンパイルにおけるエラーはプッシュが失敗する原因となります。Rails 5 アセットパイプラインのサポートについては、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 5 アプリケーションが Heroku にデプロイされました。次にお勧めするリソースを紹介します。

  • 「Ruby サポートカテゴリ​」では、Heroku での Ruby および Rails の使用に関する詳細を確認できます。
  • 「デプロイカテゴリ​」では、デプロイを効率的かつ簡単に行うことができるようにする、多くの強力な統合や機能を紹介しています。

関連カテゴリー

  • Rails のサポート
Unicorn を使用した Rails アプリケーションのデプロイ Heroku スターターガイド (Rails 6.x)

Information & Support

  • Getting Started
  • Documentation
  • Changelog
  • Compliance Center
  • Training & Education
  • Blog
  • Podcasts
  • Support Channels
  • Status

Language Reference

  • Node.js
  • Ruby
  • Java
  • PHP
  • Python
  • Go
  • Scala
  • Clojure

Other Resources

  • Careers
  • Elements
  • Products
  • Pricing

Subscribe to our monthly newsletter

Your email address:

  • RSS
    • Dev Center Articles
    • Dev Center Changelog
    • Heroku Blog
    • Heroku News Blog
    • Heroku Engineering Blog
  • Heroku Podcasts
  • Twitter
    • Dev Center Articles
    • Dev Center Changelog
    • Heroku
    • Heroku Status
  • Facebook
  • Instagram
  • Github
  • LinkedIn
  • YouTube
Heroku is acompany

 © Salesforce.com

  • heroku.com
  • Terms of Service
  • Privacy
  • Cookies
  • Cookie Preferences