Backing up your Rails MySQL DB via a Rake task
This article is the source of this code, but I’ve included some of the recommended modifications in the comments. This will back up a MySQL database (via mysqldump) into a directory of your choosing (or RAILS_ROOT/db by default), rolling automatically at 20 backups, and using your database.yml as the source of the login information (so you keep it DRY).
require 'find' namespace :db do desc "Backup the database to a file. Options: DIR=base_dir RAILS_ENV=production MAX=20" task :backup => [:environment] do datestamp = Time.now.strftime("%Y-%m-%d_%H-%M-%S") base_path = ENV["DIR"] || "db" backup_base = File.join(base_path, 'backup') backup_folder = File.join(backup_base, datestamp) backup_file = File.join(backup_folder, "#{RAILS_ENV}_dump.sql.gz") File.makedirs(backup_folder) db_config = ActiveRecord::Base.configurations[RAILS_ENV] sh "mysqldump -u #{db_config['username'].to_s} #{'-p' if db_config[ 'password']}#{db_config['password'].to_s} --opt #{db_config['database']} | gzip -c > #{backup_file}" dir = Dir.new(backup_base) all_backups = (dir.entries - ['.', '..']).sort.reverse puts "Created backup: #{backup_file}" max_backups = ENV["MAX"] || 20 unwanted_backups = all_backups[max_backups.to_i..-1] || [] for unwanted_backup in unwanted_backups FileUtils.rm_rf(File.join(backup_base, unwanted_backup)) puts "deleted #{unwanted_backup}" end puts "Deleted #{unwanted_backups.length} backups, #{all_backups.length - unwanted_backups.length} backups available" end end
I created a cron entry like so to backup my mephisto database every day at 3am (EST):
0 3 * * * cd /srv/mephisto-0.8/ && /usr/local/bin/rake db:backup RAILS_ENV=production
Of course if your running on a VPS or hosted solution, your provider is likely doing their own backups, but if you’re not, this can come in handy.
0 comments
