Lesson 3: Filesystem Snapshot Volumes on a MongoDB Serverv / Learn

Code Summary: Filesystem Snapshot Volumes on a MongoDB Server

Review the following code, which demonstrates how to create and restore a volume snapshot.

Lock the Database

The following code shows how to lock the database by using the fsyncLock() command. This will make it so nothing can be written to the database. It also flushes any write operations that have not yet been written to the disk.

mongosh

db.fsyncLock();

exit

Create a Snapshot Volume

The following code shows how to create a snapshot volume. The snapshot volume has a maximum size of 100 megabytes, and is named mdb-snapshot and backed by the MongoDB data store volume.

sudo lvcreate --size 100M --snapshot --name mdb-snapshot /dev/vg0/mdb;

Unlock the Database

The following code shows how to unlock the database by using the fsyncUnlock() command. If you forget to do this, the database will not be able to perform write operations.

mongosh

db.fsyncUnlock();

Archive the Snapshot

The following code performs a complete copy of the snapshot volume, streams the data to the gzip utility for compression, and finally redirects the output to the archive file.

exit

sudo dd status=progress if=/dev/vg0/mdb-snapshot | gzip > mdb-snapshot.gz

Restore the Archived Snapshot

The following code shows how to restore the archived snapshot. First, create a new logical volume named mdb-new:

sudo lvcreate --size 1G --name mdb-new vg0;

Next, extract the snapshot and write it to the new logical volume:

gzip -d -c mdb-snapshot.gz | sudo dd status=progress of=/dev/vg0/mdb-new

Then, stop the MongoDB service before mounting to the source directory:

sudo systemctl stop -l mongod; sudo systemctl status -l mongod;

Delete any existing MongoDB data files. This is for demonstration purposes to show how the entire deployment is restored.

sudo rm -r /var/lib/mongodb/*

Next, unmount the MongoDB deployment so that you can mount the newly restored logical volume in its place.

sudo umount /var/lib/mongodb

Mount the restored logical volume on the MongoDB database directory:

sudo mount /dev/vg0/mdb-new /var/lib/mongodb

Finally, start the MongoDB service and connect to the deployment. Run show dbs to confirm that the databases have been restored.

Here's an example:

sudo systemctl start -l mongod; sudo systemctl status -l mongod;

mongosh

show dbs