Sometimes, You want to take a backup and restore the database in the Redis server.

This tutorial explains different ways to take backup and restore.

  • take backup in one server and restore it to another server
  • Setup master-slave replication to sync data between two servers.

How to take backup and restore Redis database.

When the Redis server starts, It looks for the dump.rdb file for initial data to load into memory for cache.

Also, Redis stores the in-memory cache data in dump.rdb by default periodically.

You can use bgsave and save commands to take a snapshot of the database into dumb.rdb file.

Following are the steps to take a snapshot of the Redis database from one server, and move it to another server.

  • Open terminal

  • type the redis-cli command to open a terminal in Redis interactive shell mode

  • type config get dir command to know the location of dumb file is A:\\Java\\Redis\\dump.rdb file

    127.0.0.1:6379> config get dir
    1) "dir"
    2) "A:\\Java\\Redis"
    
  • type the save or bgsave command to take backup

You can run one of the commands below.

save stores the latest data into dumb.rdb file. It is an asynchronous operation. It blocks all clients accessing Redis instances, hence not recommended for production usage.

It returns OK as output for a successful backup.

127.0.0.1:6379> save
OK

bgsave is an asynchronous operation that runs in the background.

It starts the background thread and executes asynchronously and does not block client requests.

It is recommended for production usage.

127.0.0.1:6379> bgsave
Background saving started
127.0.0.1:6379>
  • Once the backup is completed. you can go to the target Redis server and stop the server.
  • Next, you can copy or overwrite the file to target the Redis server
  • start the target Redis server

How to replicate or copy data between two servers.

The first, step is to make sure that two Redis servers are running.

Next, run the below command in version 5 or below.

SAVEOF hostname port

In Redis version 5 or more, use REPLICAOF command.

REPLICAOF   hostname port

After running the command, It copies all data to the slave machine.

You can check and test the data using the key * command.

You can also configure the below options to master for write, slave instance for reading access.

min-slaves-to-write
min-slaves-max-lag