Lesson 4: Filesystem Archives on a MongoDB Server / Learn
Code Summary: Filesystem Archives on a MongoDB Server
Review the following code, which demonstrates how to create and restore a filesystem archive.
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 shows how to archive the snapshot. First, create a new temporary directory named mongodbsnap:
exit
mkdir /tmp/mongodbsnap
Next, mount the snapshot volume taken previously as read-only on the directory that you just created:
sudo mount -t xfs -o nouuid,ro /dev/vg0/mdb-snapshot /tmp/mongodbsnap/
Finally, use tar to create a new archive of all the files in the mongodbsnap directory:
sudo tar -czvf mdb-snapshot.tar.gz -C /tmp/mongodbsnap/ .
Restore the Archived Snapshot
The following code shows how to restore the archived snapshot.
First, create a new directory and extract the compressed tar file into the new directory:
sudo mkdir /mdb
sudo tar -xzf mdb-snapshot.tar.gz -C /mdb
Then stop the MongoDB service before updating the dbPath in the MongoDB configuration file. Then, make the mongodb user and group the owner of the mdb directory and all of its files. Otherwise, the service will fail to start.
sudo systemctl stop -l mongod; sudo systemctl status -l mongod;
sudo chown -R mongodb:mongodb /mdb
Next, open the mongod.conf file and change the dbPath to /mdb:
sudo nano /etc/mongod.conf
storage:
dbPath: /mdb
Start the MongoDB service and connect to the deployment. Then run show dbs to confirm that the databases have been restored:
sudo systemctl start -l mongod; sudo systemctl status -l mongod;
mongosh
show dbs