Rails Deploy to Heroku

by Daniel Kehoe

Last updated 26 January 2017

Here's how to deploy a Rails application on Heroku. Heroku provides low cost, easily configured Rails application hosting.

This guide is adapted from a chapter in my book series, Learn Ruby on Rails. It is said to be, "The best Rails book for beginners." Get the first book in the series for free if you'd like to get a solid understanding of Rails.

What You Need to Know

Alternatives

Rails developers sometimes use AWS (Amazon Web Services) or DigitalOcean for hosting. AWS is cheaper for high traffic websites but requires additional system administration skills. Heroku is widely preferred for convenience.

Cost

It costs nothing to set up a Heroku account and deploy as many applications as you want. You’ll pay only if you upgrade your hosting to accommodate a busy website. Heroku pricing is based on a measure of computing resources the company calls a “dyno.” Think of a dyno as a virtual server (though it is not). For personal projects, you can run your Rails application on a single dyno and never incur a charge, as long as it is not active more than 12 hours a day.

A single dyno idles after one hour of inactivity, “going to sleep” until it receives a new web request. For a personal project, this means your web application will respond with a few seconds delay if it hasn’t received a web request in over an hour. After it wakes up, it will respond quickly to every browser request.

If you want your web application running 24 hours per day and responding to every request without delay, Heroku will charge $7 per month for a “hobby” account. Heroku offers the option of adding dynos to handle more traffic for $25 per month; here’s an article that compares Heroku costs.

Git

You'll deploy to Heroku using Git commands. Git is essential to Rails development, providing version control. Developers typically push version changes to GitHub or another remote repository for collaboration and backup. You'll add Heroku as a remote repository, too, and push to Heroku when you wish to deploy. You'll need to get comfortable with Git in order to use Heroku.

Database

Beginners often use the SQLite database for Rails projects. Heroku provides a PostgreSQL database. For most projects, you simply need to modify the application Gemfile to specify SQLite for development and PostgreSQL for production. For important projects, you should install and use PostgreSQL on your local machine so your development and production environments are identical.

Development vs. Production Environments

The version of the application on your local machine is your development instance. The version of your application on Heroku is your production instance. Sometimes you will have a test instance locally and a staging instance on Heroku as well.

Specify a Ruby Version in Your Gemfile

Heroku recommends declaring a Ruby version in your Gemfile. Modify your application Gemfile to specify a Ruby version:

source 'https://rubygems.org'
.
.
.
ruby '2.4.0'
.
.
.

Use the newest stable version of Ruby for best results.

Specify a Webserver in Your Gemfile

Rails 5 specifies the Puma webserver as a default in the application Gemfile. Check that your application Gemfile specifies Puma:

source 'https://rubygems.org'
.
.
.
# Use Puma as the app server
gem 'puma', '~> 3.0'
.
.
.

Heroku recommends using Puma. Im most cases, you can use the Puma default settings without any changes to the config/puma.rb file. Heroku provides a technical reference Deploying Rails Applications with the Puma Web Server for details.

You can control Heroku platform resources by adding a Procfile to the application root directory. The Procfile is a mechanism for declaring what commands are run when your web app runs on the Heroku platform. For a simple web application, no Procfile is needed. Heroku offers documentation on Process Types and the Procfile.

Prepare Your Gemfile for PostgreSQL

If you are using PostgreSQL in development, your Gemfile is already set up for Heroku. However, if you are using the SQLite database in development, you'll need to modify the Gemfile for Heroku.

If you are using SQLite, find the line:

gem 'sqlite3'

And replace it to indicate the SQLite gem is for use in development only:

group :development do
  gem 'sqlite3'
end

Add the PostgreSQL gem for use in production only:

group :production do
  gem 'pg'
end

When we deploy, Heroku will read the Gemfile and install the gem in the production environment. We'll run bundle install with the --without production argument so we don't install the new gem locally:

$ bundle install --without production

The flag --without production allows you to skip local installation of the pg gem; otherwise, you will have to install PostgreSQL locally (the pg gem won’t install if PostgreSQL is not installed).

You'll see:

.
.
.
Gems in the group production were not installed.
Use `bundle show [gemname]` to see where a bundled gem is installed.

Commit your changes to the Git repository and push to GitHub:

$ git add -A
$ git commit -m "gems for Heroku"
$ git push

You must commit the changes to the Git repository. Heroku only gets the files that are committed to the Git repo.

Sign Up for a Heroku Account

To deploy an app to Heroku, you must have a Heroku account. Visit https://id.heroku.com/signup/devcenter to set up an account.

Be sure to use the same email address you used to configure Git locally. You can check the email address you used for Git with:

$ git config --get user.email

Using Someone Else’s Account

You may want to deploy an application to an account that belongs to someone other than yourself (for example, your employer or a client). If you are using a client’s or employer’s Heroku account, you won’t be able to push your application to Heroku until you’ve added yourself as a collaborator. After you create an app on Heroku, log in to your client’s account on Heroku. Under "Personal Apps" you’ll see the name of the app you’ve created; click "Access" and add yourself as a collaborator.

Heroku Toolbelt

Heroku provides a command line utility for creating and managing Heroku apps. You only need to install it once and it will be available whenever you need to set up an application for deployment to Heroku.

Visit https://toolbelt.heroku.com/ to install the Heroku Toolbelt. A one-click installer is available for Mac OS X, Windows, and Linux.

The installation process will install the Heroku command line utility. It also installs the Foreman gem which is useful for duplicating the Heroku production environment on a local machine. The installation process will also make sure Git is installed.

To make sure the Heroku command line utility is installed, try:

$ heroku version
heroku-toolbelt/...

You'll see the heroku-toolbelt version number.

You should be able to login using the email address and password you used when creating your Heroku account:

$ heroku login
Enter your Heroku credentials.
Email: [email protected]
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

The Heroku command line utility will create SSH keys if necessary to guarantee a secure connection to Heroku.

Heroku Create

The Heroku Toolbelt gives you command-line tools to set up an application for deployment to Heroku. You can set up your application for Heroku at any time.

Be sure you are in your application root directory and you've committed your work to the Git repository.

Use the Heroku create command to create and name your application.

$ heroku create myapp

Replace myapp with something unique. Heroku demands a unique name for every hosted application. If it is not unique, you'll see an error, "name is already taken." The name must start with a letter and can only contain lowercase letters, numbers, and dashes.

If you don't specify your app name (myapp in the example above), Heroku will supply a placeholder name. You can easily change Heroku's placeholder name to a name of your choice with the heroku apps:rename command (see Renaming Apps from the CLI).

Don't worry too much about getting the "perfect name" for your Heroku app. The name of your Heroku app won't matter if you plan to set up your Heroku app to use your own domain name. You'll just use the name for access to the instance of your app running on the Heroku servers; if you have a custom domain name, you'll set up DNS (domain name service) to point your domain name to the app running on Heroku.

The heroku create command sets your Heroku application as a Git remote repository. That means you'll use the git push command to deploy your application to Heroku.

You can confirm you've set up your application for deployment to Heroku by displaying the remote repositories. You'll see both Github ("origin") and Heroku remote repositories:

$ git remote -v
heroku    https://git.heroku.com/myapp.git (fetch)
heroku    https://git.heroku.com/myapp.git (push)
origin    https://github.com/DanielKehoe/myapp.git (fetch)
origin    https://github.com/DanielKehoe/myapp.git (push)

Adding Heroku to a Clone of a Previously Deployed Application

You might git clone a repo for work on a new development machine. In this case, the Heroku remote exists on the original repository but not the cloned repo. If you wish to push to an existing Heroku application from a cloned repo, you must add the Heroku remote repository with the correct application name. Assuming the Heroku app is named myapp, here's how:

$ heroku git:remote -a myapp
Git remote heroku added.

You can confirm you've added a Heroku remote:

$ git remote -v
heroku    https://git.heroku.com/myapp.git (fetch)
heroku    https://git.heroku.com/myapp.git (push)
origin    https://github.com/DanielKehoe/myapp.git (fetch)
origin    https://github.com/DanielKehoe/myapp.git (push)

You can find alternative approaches described in a Stack Overflow answer, How to link a folder with an existing Heroku app.

Set Heroku Environment Variables

In a typical Rails application, configuration values are obtained from the config/secrets.yml file, which contains Unix environment variables which are set in a local .bash_profile or .bashrc file. Your application may be obtaining usernames, passwords, or API keys for external services from the Unix shell environment. It’s a recommended practice to avoid recording sensitive information in your application code where it might be exposed publicly on a GitHub repo.

Heroku doesn't have a .bash_profile or .bashrc file, so you'll need a way to set environment variables on Heroku. You can use the heroku config:add command. Look in your config/secrets.yml file for the environment variables you need to set. For example:

$ heroku config:add SENDGRID_USERNAME='example'
$ heroku config:add SENDGRID_PASSWORD='secret'
$ heroku config:add MAILCHIMP_API_KEY='my-key'
$ heroku config:add MAILCHIMP_LIST_ID='mylistid'
$ heroku config:add OWNER_EMAIL='[email protected]'

You don't need to set SECRET_KEY_BASE, even though it is in your config/secrets.yml file. Heroku sets it automatically.

Check that the environment variables are set with:

$ heroku config

See the Heroku documentation on Configuration and Config Vars for more information.

Push to Heroku

Now you can deploy your application to Heroku.

Be sure to commit any recent changes to the Git local repository before you push to Heroku.

You commit your code to Heroku just like you push your code to GitHub.

Here's how to push to Heroku:

$ git push heroku master

You may see a message, "The authenticity of host 'heroku.com' can't be established. Are you sure you want to continue connecting (yes/no)?". You can answer "yes" and safely continue.

The push to Heroku takes several minutes. You'll see a sequence of diagnostic messages in the console, beginning with:

remote: Compressing source files... done.

and finishing with:

remote: Verifying deploy.... done.

Each time you update your application and push to GitHub, you can deploy the update to Heroku with git push heroku master.

Database Migration

Most Rails applications require configuration of a database. After pushing the application to Heroku, you must run any needed database migrations:

$ heroku run rake db:migrate

After the database migration, you should seed the database if you have code in the db/seeds.rb file:

$ heroku run rake db:seed

The rake db:seed command will populate the database with initial data.

Keep in mind that your local database and the Heroku database do not have the same data. Your application is running on different servers with different databases.

Visit Your Site

Your application will be running at http://my-app-name.herokuapp.com/. You can open any web browser and visit the site. For a shortcut, you can open your default web browser and visit your site from the command line:

$ heroku open

If you're using hosted development such as Cloud9, you'll need to open a browser manually to visit the site.

Application Status

You can check the status of your Heroku application:

 $ heroku ps
Free dyno hours quota remaining this month: 559h 56m (55%)
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: idle 2017/01/26 21:10:24 +0800 (~ 3m ago)

You also can log into your Heroku account and see a dashboard that details resources and settings for each deployed application.

Customizing and Add-ons

For a real application, you'll likely want to use your own domain name for your app.

See Heroku's article about custom domains for instructions.

You may also want to improve website responsiveness by adding page caching with a content delivery network such as CloudFlare. CloudFlare can also provide an SSL connection for secure connections between the browser and server.

Heroku offers many add-on services. These are particularly noteworthy:

  • Adept Scale - automated scaling of Heroku dynos
  • Rollbar - exception tracking and logging

Troubleshooting

When you get errors, troubleshoot by reviewing the log files:

$ heroku logs

If necessary, use the Unix tail flag to monitor your log files. Open a new terminal window and enter:

$ heroku logs -t

to watch the server logs in real time.

Asset Pipeline

Previous versions of Rails required configuration of the Rails asset pipeline for Heroku. Precompiling assets is not required for Rails 5. If CSS styling is missing from your web pages, it is a likely indicator that the asset pipeline is not working or assets are not compiled. If you want to learn more about the asset pipeline, refer to the Rails Guide on the Asset Pipeline or an article from LaunchSchool.

Database Reset

Heroku doesn’t support rails db:reset.

Need to reset your Heroku PostgreSQL database? Here’s how:

$ heroku pg:reset DATABASE

Don’t forget to restart your application or you won’t see any changes:

$ heroku restart

More Information

Heroku provides detailed instructions for Getting Started with Rails 5.x on Heroku.

results matching ""

    No results matching ""