Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Rake task to back up heroku database and restore it locally.
namespace :db do
desc "Backs up heroku database and restores it locally."
task import_from_heroku: [ :environment, :create ] do
HEROKU_APP_NAME = nil # Change this if app name is not picked up by `heroku` git remote.
c = Rails.configuration.database_configuration[Rails.env]
heroku_app_flag = HEROKU_APP_NAME ? " --app #{HEROKU_APP_NAME}" : nil
Bundler.with_clean_env do
puts "[1/4] Capturing backup on Heroku"
`heroku pg:backups capture DATABASE_URL#{heroku_app_flag}`
puts "[2/4] Downloading backup onto disk"
`curl -o tmp/latest.dump \`heroku pg:backups public-url #{heroku_app_flag} | cat\``
puts "[3/4] Mounting backup on local database"
`pg_restore --clean --verbose --no-acl --no-owner -h localhost -d #{c["database"]} tmp/latest.dump`
puts "[4/4] Removing local backup"
`rm tmp/latest.dump`
puts "Done."
Copy link

ssaunier commented Nov 13, 2014

Copy this file in you rails app to the lib/tasks repository. Make sure you have the heroku PG Backups add-on in place on your app. Then you can run:

$ rake db:import_from_heroku

This will remove all your local data and replace it with the production data on your local database.

Copy link

augnustin commented Dec 19, 2014


Copy link

jmsevold commented Mar 9, 2015

On the project I am working on, we have both our development and production database on Heroku. When I ran this task, it pulled down the development database dump. Is there anyway I could specify the production database within this task?

Copy link

ssaunier commented Jul 20, 2015

@jmsevold: you can add --app YOUR_PRODUCTION_APP to line 7 (heroku pg:backups capture) of the script to specify which database app you want to dump.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment