DEV Community

Regular 🍟
Regular 🍟

Posted on


A Better Way to Deploy Rails app on Heroku

Time: 2021-04-03 23:44 UTC+8:00

Author: vonhyou

This article introduces the professional way of deploying Rails app on Heroku.

Force SSL

Modify the file config/environments/production.rb in your Rails app:

# Uncomment this 
config.force_ssl = true
Enter fullscreen mode Exit fullscreen mode

Heroku provide free ssl certificate and it's not necessary to do something else.

Switch to Puma

  1. Add a gem called puma to the Gemfile and install it.
  2. Rewrite the file config/puma.rb
# Puma configuration file.
max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count }
threads min_threads_count, max_threads_count
port        ENV.fetch("PORT") { 3000 }
environment ENV.fetch("RAILS_ENV") { ENV['RACK_ENV'] || "development" }
pidfile ENV.fetch("PIDFILE") { "tmp/pids/" }
workers ENV.fetch("WEB_CONCURRENCY") { 2 }
plugin :tmp_restart
Enter fullscreen mode Exit fullscreen mode
  1. Create Procfile
$ touch ./Procfile
Enter fullscreen mode Exit fullscreen mode
  1. Write Procfile
web: bundle exec puma -C config/puma.rb
Enter fullscreen mode Exit fullscreen mode
  1. Configurate database for production
# SQLite. Versions 3.8.0 and up are supported.
#   gem install sqlite3
#   Ensure the SQLite 3 gem is defined in your Gemfile
#   gem 'sqlite3'
default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

  <<: *default
  database: db/development.sqlite3

# 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.
  <<: *default
  database: db/test.sqlite3

  adapter:  postgresql
  encoding: unicode
  pool:     <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  database: <APPNAME>_production
  username: <APPNAME>
  password: <%= ENV['<APPNAME>_DATABASE_PASSWORD'] %>
Enter fullscreen mode Exit fullscreen mode

Declare Ruby Version

Modify Gemfile

ruby '2.6.5' # your version
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

juanvqz profile image
Juan Vasquez

Why is better puma for heroku?

vonhyou profile image
Regular 🍟

It depends, according to the documentation:

... Puma is a webserver that competes with Unicorn and allows you to handle concurrent requests. Puma uses threads, in addition to worker processes, to make more use of available CPU. You can only utilize threads in Puma if your entire code-base is thread safe. Otherwise, you can still use Puma, but must only scale-out through worker processes.

Link: Deploying Rails Applications with the Puma Web Server

juanvqz profile image
Juan Vasquez

I have been using puma because it's the "default" way in Heroku, at least for me it's super easy to use it.