Member-only story

Automatically backup MongoDB to Amazon S3 via cron

Tom Nagle
2 min readApr 23, 2018

--

This tutorial has been written for Ubuntu and tested on Ubuntu 14.04 LTS. As a result of following this tutorial your server will:

  1. Dump each MongoDB database
  2. Sync the backups with Amazon S3
  3. Run the above command every night with a cron job

Step 1) Create a shell script to dump the database

cd ~
mkdir scripts
cd scripts
nano db_backup.sh

Paste in the following script

#!/bin/bash
DIR=`date +%d-%m-%y`
DEST=~/db_backups/$DIR
mkdir $DEST
mongodump -h localhost:27017 -d my_db_name -o $DEST

chmod the script so its can be executed

chmod +x ~/scripts/db_backup.sh

The last line should be duplicated for each local database that you want to backup.

Step 2) Create a shell script to sync the database backups with Amazon S3

nano db_sync.sh

Paste in the following script

#!/bin/bash
/usr/local/bin/aws s3 sync ~/db_backups s3://my-bucket-name

chmod the script so its can be executed

chmod +x ~/scripts/db_sync.sh

Step 3) Create the folder for the database dumps to go

cd ~
mkdir db_backups

Step 4) Configure the AWS Command Line Interface

--

--

Tom Nagle
Tom Nagle

Written by Tom Nagle

I am a full stack JavaScript developer, living in Melbourne, Australia. My preferred stack is Mongoose, TypeScript, Node.js, React & GraphQL.

No responses yet