Backup database and other attachments in ROR


Related Resources

  1. rsync :
  2. Crontab :
  3. “Linux Crontab 定时任务 命令详解” :
  4. [rubygem]“backup”:
  5. [rubygem]“whenever”:

Automatically backup on the remote server:

Let’s firstly assumpt:

  1. You have a site named “ ”;
  2. You can login to it through a username “ deploy ”, and its password is “ password ”;
  3. You located the contents of your site in /var/www/example/;
  4. Your database server is Mysql , and the database for your site is example_production.

1. SSH login:

2. Install the backup:

3. Prepare directories for backup files:

4. Generate and edit backup script:

Input the below content:

# encoding: utf-8, 'Dumping example Production Database') do
 split_into_chunks_of 250

 database MySQL do |db| = "example_production"
 db.username = "" # Replace the blank string with your real username
 db.password = "" # Replace the blank string with your real password = "localhost"
 db.port = 3306
 db.socket = "/var/run/mysqld/mysqld.sock"
 db.additional_options = ["--quick", "--single-transaction"]

 store_with Local do |local|
 local.path = "/var/www/example/backup/db"
 local.keep = 10

 compress_with Gzip

Run backup command to confirm that your config works:

Attention : Remember to update the config file if you have changed the username and/or password of the database.

5. Install whenever:

6. Generate a schedule.rb file with whenever:

The last command will create a new file named “schedule.rb” under config/ directory.

7. Add a daily task:

Open the file to edit:


set :output, "~/Backup/example_whenever.log" # This is important, it can help you to find the reason when failed to backup the database
every :day do
 command "cd ~/Backup && backup perform -t example_db"

8. Update whenever task into crontab:

9. Check whether the task is updated successfully or not:

If successed, you should see your new task shown at the bottom of the file.

Synchronize remote backups every day automatically by rsync and crontab:

Attention : Below operations are played on a different server, which is used to sync files. We assumpt its domain is and the username is deploy.

1. SSH login:

2. Write a synchronize shell script:

Input the below contents into the new file named ‘’:

and then, assign the scripe execution authority:

Run the script to ensure everything works well:

Attention: Because it is required to be authorized to access the targer server, you should remember to copy your ssh public key to the target server(such as, ) before you can sync files.

3. Open user’s crontab config file:

Append the below task at the end:

Ok, that’s all. The rest work is that remember to check if there is any backups generated.

社区准则 博客 联系 反馈 状态