Heroku Nightly Database Backups with Cron

I thought I’d share a quick tip how to do nightly database backups with Cron at Heroku.

First you’ll need to enable Cron for your Heroku application. That can be done from Heroku control panel and the basic version is free. It runs once per day which is enough for this use case.

The next thing you have to do is add the Heroku gem to your Gemfile:

gem 'heroku'

The last step is to create lib/tasks/cron.rake and copy the below code:

HEROKU_USERNAME = "HEROKU_USERNAME"
HEROKU_API_KEY  = "HEROKU_API_KEY"
HEROKU_APP      = "HEROKU_APP"

task :cron do

  require "heroku"
  require "heroku/command"
  require "heroku/command/pgbackups"

  Heroku::Auth.credentials = [HEROKU_USERNAME, HEROKU_API_KEY]
  Heroku::Command.load
  Heroku::Command::Pgbackups.new([],
    {:app => HEROKU_APP, :expire => true}).capture

end

You can get HEROKU_USERNAME and HEROKU_API_KEY from ~/heroku/.credentials. Probably HEROKU_API_KEY is just an hashed password and not really an API key, but it will work just fine :)

Just remember it’s not really public information so don’t use it in open source projects or anything big – it’s probably fine for personal and small projects where you are not worried about someone stealing your Heroku login – pretty much what the free Heroku package is for anyway.

With the shared database you are allowed 2 backups for free and the above script will always delete the oldest one before capturing a new backup. This means that you can have nightly backups with 2 days history for free.

Enjoy :)

Tarmo Lehtpuu
Tarmo is the swiss army knife Software Engineer. His deep knowledge on wide range of technologies makes him an efficient problem solver. In addition to Ruby on Rails, he enjoys developing iOS Apps.

Comments are closed here.

Liked this post?

There’s more where that came from. Follow us on Facebook, Twitter or subscribe to our RSS feed to get all the latest posts immediately.