Running Rails migrations automatically on Heroku

How you can tell Heroku to automatically run your Rails migration (and how to do it manually if you need)

Heroku is a common hosting solution for many Rails projects. Today I’m going to show you how you can ask Heroku to run Rails migrations for you automatically. I will also share the commands you need to run a manual migration.

If you’re just here for the code you need, add this to your Procfile;

release: rake db:migrate

If you don’t know what a Procfile is or what that command means, stick around 😊

Heroku’s Procfile

Heroku uses a text file named Procfile to let you tell it which web server to use, what workers to run and, importantly for us, which tasks to run before a new release is deployed.

The format of the Procfile is a list of key: value pairs.

Here is a sample Procfile from one of our projects. It specifies the web server, what to do before a release, and how to run a worker.

web: bundle exec puma -C config/puma.rb
release: rake db:migrate
worker: bundle exec sidekiq -c 2

We want to run rake db:migrate before Rails is released because you don’t want people using your application without the correct database setup.

You don’t have to call rake db:migrate. If you had a script you run that does migrations in a slightly different way, you could call bin/my_migration_script.

Running migrations manually

Heroku has a tool that allows you to interact with your application from your computer’s command line, Heroku CLI.

Once installed, you get access to many small tools for interacting with your Heroku application, including run.

[heroku run](/running-commands-on-heroku/) rake db:migrate --app my_awesome_app

This command will spin up a temporary instance of your application and immediately run rake db:migrate; once it has completed, Heroku will destroy the temporary instance.

The run command is excellent for running a Rails console too;

heroku run rails c --app my_awesome_app

In both of these examples, --app my_awesome_app refers to the name of the application within Heroku.

This article is a part of the "Rails migrations" series


Recent posts View all

Web Dev

Creating draft posts in Jekyll

How to create and develop with draft posts in Jekyll

Ruby

Forcing a Rails database column to be not null

How you can force a table column to always have something in it with Rails