Backup and Restore a MongoDB deployed on Cloudfoundry


Posted by Steven

Earlier, I wrote an article about how to create a connection to a database service in Cloudfoundry. The reason for this was to backup and restore a Mongo database, which is the topic of this article.

1. SSH-tunnel

First, built up an SSH-tunnel (details see here):

  1. cf allow-space-ssh myspace
  2. cf enable-ssh myapp
  3. cf restage myapp
  4. cf ssh myapp -L 27017:ENDPOINT:27017

As mentioned here, it is a good idea to deploy a dummy application that only serves as an SSH endpoint and can be restarted without disrupting business processes.

2. Backup

The "Mongo Database Tools" include two applications for backup and restore. Here is the source (in different versions) of these tools, here's the official documentation and here is the download. Because older versions of the standalone-tools cannot be downloaded separatly, it is necessary to download the whole MongoDB Community Server from here.

With that, the two applications mongodump and mongorestore should be available - in the right version! - on the local machine.

Using a bash syntax and the full paths for documentation, this creates the dump:

  1. /C/tools/mongodb-win32-x86_64-2008plus-ssl-3.6.18/bin/mongodump.exe --uri mongodb://myusername:mypassword@127.0.0.1:27017 --ssl --sslAllowInvalidHostnames --sslCAFile ifneeded.pem

Use "cf env myapp" to determine the download location of the CA file, if necessary.

Executing mongodump will create a folder named "dump".

3. Restore

The created dump can now be stored away for later usage or be used to copy the data onto another Mongo database. For this, use the steps above to create a connection to the new target database so that it is mapped to the local port 27017. Now, mongorestore can apply the dump:

  1. /c/tools/mongodb-win32-x86_64-2008plus-ssl-3.6.18/bin/mongorestore.exe dump/ -u myusername --drop --ssl --sslAllowInvalidHostnames --sslCAFile ifneeded.pem

It is important to provide a username that has the restore-role, as documented here and here. This will prevent errors like "error: not authorized on ... to execute command".

The command above has the drop-flag enabled which means that all collections included in the backup will be deleted before importing the backup. This will prevent the "E11000 duplicate key error collection", see here.

Category: 
Share: