Syncing your development and production databases

Syncing your local database with your production environment is a smart thing to do.

Here are few reasons why:

  1. When tuning for speed, you're working with the same amount of data that production is dealing with (I talk about this in my post on tweaking your Rails app for performance)
  2. It reduces the differences between development and production environments, making bugs easier to reproduce
  3. It keeps your user accounts and authentication in sync

In order to making syncing databases as easy as possible, we can set up a simple rake task to do the heavy lifting for us.


namespace :db do  
  desc "Syncs local database with production"
  task :sync do
    puts 'Syncing local database with production...'

    db_config = Rails.configuration.database_configuration
    database_name = db_config['development']['database']

      `heroku pgbackups:capture`
      `curl -o latest.dump \`heroku pgbackups:url\``
      `pg_restore --verbose --clean --no-acl --no-owner -h localhost -d #{database_name} latest.dump`
      `rm latest.dump`

This requires having Heroku's command line toolbelt installed, pgbackups available on your Heroku app and postgres installed.

I used Postgres and Heroku in my example, but this approach can be applied to any database and hosting provider.

Andrew Allen

Author of, Software Engineer @Munchery, Former startup founder.

comments powered by Disqus