carlessanagustin
2/15/2013 - 5:02 PM

MongoDB Automatic Backup to Amazon S3 with Crontab and s3cmd. Red Hat Linux on Amazon EC2

MongoDB Automatic Backup to Amazon S3 with Crontab and s3cmd. Red Hat Linux on Amazon EC2

sudo yum --enablerepo epel install s3cmd

#to configure s3cmd
s3cmd --configure
#every day at 01h 00m
00 01 * * * /bin/bash /home/ec2-user/mongodb_to_s3_backup.sh
#!/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())"