Software engineering, open source, community and passion
Scheduled Backups with Clockwork and Backup Gem
Today I am here to demonstrate a solution I have used to backup a Rails application to Amazon S3.
A popular library to perform backups in Ruby world, is Backup, it has a lot of options (for storage, compression, notification..) and seemed great to me.
Having our backup gem chosen, it's time to pick a gem to deal with scheduled jobs in order we can schedule automatic backups. As Clockwork already was in project's Gemfile, I used it.
Setting up Environment
It isn't recommended include Backup gem in project's main Gemfile, a solution is to create an isolated environment to this gem.
Firstly, let's install the gem:
Now, you will need to create the below structure:
-my_rails_app
|-vendor
|-backup
|-Gemfile
Inside vendor/backup/Gemfile you drop:
This Gemfile is just to Bundler recognize the folder as an isolated env.
Generating Backup Model
In my case, I generated a simple backup model in order to backup a PostgreSQL database, compress the dump and send to Amazon S3:
Fill in your credentials (taken from your .yml files) in the recently created file inside models folder:
We will need set our DIR variable in config.rb file also:
And after, run it:
It should works, access your bucket and check out your dump..
Scheduling Backups
Finally, I scheduled backups in app/clock.rb file:
Here, we run the perform command inside our isolated env using with_clean_env, that ensure we are not in application's env.
You can also create a rake task like this in lib/tasks/db.rake:
However, you will have to create a method inside app/clock.rb to invoke the rake:
After all, you must have your automatic backup scheduled successfully.