Deploying a Rails app on Heroku with PostgreSQL and MongoDB

This may sound like an easy task, because there is plenty of documentation available on the web, but putting all the pieces together and getting a working app can be sometime an tough job.

Creating a Heroku app with support for MongoDB and PostgreSQL

For this you can use Heroku CLI available with Heroku Toolbel. Download, install for your platform and login. Then issue the following command in the folder with your app:

heroku create MySampleApp

Next we want to install 2 add-ons:

heroku addons:create mongolab
heroku addons:create heroku-postgresql:hobby-dev

Configuring app for running on Heroku

A Rails app when deployed to Heroku will run in production mode and load settings that were defined for production. Few steps are required here. First open your gem file and add the following gems to production group.

gem 'rails_12factor' # helps with Heroku log system
gem 'puma' # Production HTTP server
gem 'pg' # PostgreSQL support

Mongo gem is something you likely already have if you are using Rails with Mongo. For me this was added by MongoMapper my ORM for Ruby and Mongo. After updating gem file make sure you run this command to update gemfile.lock:

bundle install --without production

You may have noticed that we used puma gem that enables our app to run within the modern Puma web sever. Little configuration is required for Puma. Add a new file named puma.rb in your config folder, and copy the content from here. Next in the root folder create a new file named Procfile with the following content:

web: bundle exec puma -C config/puma.rb

Don’t forget to add the two files you just created to git.

SQL database settings are loaded from config/database.yml. Looking at production section of this file you can see that it is configured to use sqlite3 adapter. But in reality it won’t be used because the add-on we installed heroku-postgresql has defined a special environment variable named DATABASE_URL and if this is defined, it will be used with priority. To see other details about your heroku environment you can run heroku config -s.

Since my project is using MongoMapper this will load mongo related settings from config/mongo.yml. In this file we need to configure production section and define connection URL, based on another env. variable defined by mongolab add-on.

uri: <%= ENV['MONGOLAB_URI'] %>

Deploy on Heroku

At this point you have finished configuring the app and you can push to deploy on Heroku. First, commit your changes and then run:

git push heroku master

To check the live logs from Heroku use heroku logs -t. Let me know if this helped. Or feel free to ask any questions.

More lectures:

Written by on March 9, 2017.