How to Use the Redis Backup File (RDB)
Redis Backup (RDB) is a point-in-time snapshot of the Redis in-memory database stored as a binary file. It contains a serialized representation of the data and metadata, such as version information and checksums.
The RDB file can restore the Redis database to its exact state when the backup was created. It is typically created using the SAVE
or BGSAVE
commands and can be configured to occur automatically at regular intervals or when certain conditions are met. RDB files are often used for disaster recovery and to migrate Redis data between different instances or environments.
In this tutorial, we will learn how to work with the Redis Database Backup to save the data stored in the memory to the system’s disk and perform restorations from the RDB.
Redis Backup Data
In Redis, we can back up the current dataset using the SAVE
command. The command allows us to create a snapshot of the data in the selected dataset. Keep in mind that the data is saved as a binary file in the format of dump.rdb
file.
We can run the save command as shown:
127.0.0.1:6379> SAVE
OK
Once we run the command above, Redis will return an OK
message indicating that the operation has been completed successfully.
If any errors are encountered during the backup process, Redis will print a message showing the error type in the command, as demonstrated in the example below:
127.0.0.1:6379> SAVE 0
(error) ERR wrong number of arguments for the 'save' command
You can verify that the file is created by listing the files and directories in your home directory using the ls -la
command.
-rw-r--r-- 1 root root 1123456 Feb 14 14:30 dump.rdb
It is good to keep in mind that the SAVE
command is synchronous. This means it will block all operations until the backup operation is complete.
To resolve this, we can use the BGSAVE
command. This is the asynchronous equivalent of the SAVE
command. It works in the background as a child process, preventing the command from blocking already running processes.
127.0.0.1:6379> BGSAVE
Background saving started
Restoring Redis Data From RDB
Once we back up data, we need a way to restore it if necessary. To restore a Redis database from a dump.rdb file.
Start by navigating to the location of your Redis dump.rdb file:
cd ~
Next, stop the redis service with the command:
sudo service redis-server stop
Move the Redis dump.rdb file to the root directory of the Redis server:
sudo mv dump.rdb /var/lib/redis
Once you have successfully moved the file, you can start the Redis server:
sudo service redis-server start
This should force Redis to import the data during the launch and restore the stored data.
Conclusion
In this tutorial, we learned how to use the Redis Backup File to back up and restore the data stored in a Redis server.