Skip to content

Instantly share code, notes, and snippets.

@lazarofl
Last active April 19, 2022 05:06
Show Gist options
  • Save lazarofl/4961746 to your computer and use it in GitHub Desktop.
Save lazarofl/4961746 to your computer and use it in GitHub Desktop.
MongoDB Automatic Backup to Amazon S3 with Crontab and s3cmd. Red Hat Linux on Amazon EC2
#!/bin/bash
#Force file syncronization and lock writes
mongo admin --eval "printjson(db.fsyncLock())"
MONGODUMP_PATH="/usr/bin/mongodump"
MONGO_HOST="prod.example.com"
MONGO_PORT="27017"
MONGO_DATABASE="dbname"
TIMESTAMP=`date +%F-%H%M`
S3_BUCKET_NAME="bucketname"
S3_BUCKET_PATH="mongodb-backups"
# Create backup
$MONGODUMP_PATH -h $MONGO_HOST:$MONGO_PORT -d $MONGO_DATABASE
# Add timestamp to backup
mv dump mongodb-$HOSTNAME-$TIMESTAMP
tar cf mongodb-$HOSTNAME-$TIMESTAMP.tar mongodb-$HOSTNAME-$TIMESTAMP
# Upload to S3
s3cmd put mongodb-$HOSTNAME-$TIMESTAMP.tar s3://$S3_BUCKET_NAME/$S3_BUCKET_PATH/mongodb-$HOSTNAME-$TIMESTAMP.tar
#Unlock databases writes
mongo admin --eval "printjson(db.fsyncUnlock())"
#every day at 01h 00m
00 01 * * * /bin/bash /home/ec2-user/mongodb_to_s3_backup.sh
sudo yum --enablerepo epel install s3cmd
#to configure s3cmd
s3cmd --configure
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment