Senior Manager, Technical Support at Heroku / Salesforce. Former full-time traveler. Current homesteader. Huge fan of @emccartie.

Copy Heroku Database To Local

I’ve had a few Heroku projects where it’s been really nice to copy production data to my local database for development. Obviously, there are a few security concerns with this method (make sure the data in your project should be on your local machine – don’t do this if you’ve got any sensitive data!).

If you’re ok with having that data locally, you can add this script at lib/tasks/database.rake

namespace :db do

  desc "Copy production database to local"
  task :copy_production => :environment do

    # Download latest dump
    system("wget -O tmp/latest.dump `heroku pg:backups public-url -q`")

    # get user and database name
    config   = Rails.configuration.database_configuration["development"]
    database = config["database"]
    user = config["username"]

    # import
    system("pg_restore --verbose --clean --no-acl --no-owner -h localhost -d #{database} #{Rails.root}/tmp/latest.dump")
  end

end

With that in place, you can run the task with

$ rake db:copy_production

This will grab your latest Postgres backup and save it locally to tmp/latest.dump. It then grabs your local DB credentials and performs a pg_restore to restore the dump file to your local database.

Enjoy!

© 2017 Jon McCartie