Introduction
As defined from the official Redis website:
"Redis is an open source, in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs and geospatial indexes with radius queries."
Redis data is very fast to write to and read from since it only lives in memory. Redis provides RDB persistence which is the simplest Redis persistence mode that performs point-in-time snapshots of the dataset at specified intervals when specific conditions are met to which the dataset is saved in a dump.rdb file to the disk by default.
This means that it will do a complete copy of what is in memory at some points in time like for example, a new snapshot has been created given that the previous snapshot was created more than 3 minutes ago and there are 100 new writes created already. Conditions like this are controllable by the user configuring the Redis instance. The .rdb file is a binary representation of the in-memory storage which is sufficient to easily restore different versions of the dataset completely which is perfect for backups in case of disasters.
Redis made it so easy for us to backup data since we can backup or copy database while the Redis server is running.
- Location of the Redis Data Directory
First, we have to locate the Redis data directory. Since Redis stores data in a directory on the server, we need to find the location of the data that we want to backup.
In Linux, the Redis database directory by default can be found in:
/var/lib/redis
But if the Redis data location was changed or if you just want to be sure, you can locate it by this command:
sudo locate *dump.rdb
- Saving the Database State
Before doing the backup, we have to make sure that the backup is fully up to date by saving the data first.
- Open the Redis command line
- Simply issue the save command:
save
You can skip this step if losing a small of data is acceptable to you.
- Backup the Redis Data
Since we can backup the database file while Redis server is running, we can perform backup by simply typing this:
sudo cp /var/lib/redis/dump.rdb /home/redis/backup
Now, let’s automate the backup using cron.
- Open the crontab: sudo crontab –e
- Add this entry:
16 0 * * * cp /var/lib/redis/dump.rdb /home/backup/backup_$(date +\%Y\%m\%d\%H\%M\%S).rdb
This cron entry will perform Redis backup everyday at 12:16 AM. To guide you on how to schedule with cron, see below:
The output of the backup should look like this: