MongoDB automatic backups
Update: Remotespace.io no longer exists :(
When building Remotespace.io I needed a datastore for all the articles I would be posting. After some consideration I decided to use MongoDB for this and in this post I'll explain how I set up a basic automatic backup system.
First I had to read up on how to dump MongoDB databases. This turned out to be simple, I could just do
mongodump -d DB_NAME -o OUTPUT_LOCATION
Now I had to figure out where I could store the backups. My first thought was to put them in a Dropbox folder. I checked out the Dropbox developer API site and it turned out that they had a pretty nice URL API I could use. After following their documentation and registering my app I came up with the following curl request to upload backups
curl -X POST https://content.dropboxapi.com/2/files/upload \
--header "Authorization: Bearer TOKEN" \
--header "Dropbox-API-Arg: {\"path\": \"/UPLOAD_FILE_PATH\",\"mode\": \"overwrite\",\"autorename\": false,\"mute\": false}" \
--header "Content-Type: application/octet-stream" \
--data-binary @BACKUP_FILE
Notice that we overwrite old files. This way we will always have seven days of backup since we'll use the day-of-week as filename.
To put it all together I made this simple shell script that will run mongodump, zip the backup and finally upload it to Dropbox.
mongodump -d DB_NAME -o OUTPUT_LOCATION
OUT=$(date +%u).zip
zip -r /BACKUP_FILE_PATH/$OUT OUTPUT_LOCATION
curl -X POST https://content.dropboxapi.com/2/files/upload \
--header "Authorization: Bearer TOKEN" \
--header "Dropbox-API-Arg: {\"path\": \"/$OUT\",\"mode\": \"overwrite\",\"autorename\": false,\"mute\": false}" \
--header "Content-Type: application/octet-stream" \
--data-binary @/BACKUP_FILE_PATH/$OUT
Finally, I added the following line to my crontab to make it run every day 5 minutes after midnight.
5 00 * * * ./PATH_TO_THIS_SCRIPT
Of course, if you want to use this you have to change all the uppercase placeholder names to your desired ones.
If you got any questions or just want to chat, hit me up on Twitter @drikerf.