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):
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:
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:
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.