Here is the full content of your Automated MongoDB Backup to Cloudflare R2 documentation in .docx format, provided as plain text so you can copy and paste it directly into Microsoft Word:
This project sets up an automated backup system for MongoDB using a Bash script and cron, with backups securely uploaded to Cloudflare R2 via the AWS CLI.
- MongoDB installed and running
- Cloudflare R2 bucket created (e.g.,
mongo-backups) - AWS CLI configured for R2 with a profile (
r2) tar,cron, andbashavailable on the Linux system
aws configure --profile r2When prompted, provide:
- Access Key ID
- Secret Access Key
- Region (e.g.,
auto) - Output format (e.g.,
json)
Edit or create ~/.aws/config:
[profile r2]
region = auto
s3 =
endpoint_url = https://<ACCOUNT_ID>.r2.cloudflarestorage.comReplace <ACCOUNT_ID> with your actual R2 account ID.
This script performs the following:
- Dumps MongoDB database using
mongodump - Compresses the dump into a
.tar.gzfile - Uploads the archive to R2 using
aws s3 cp - Logs the backup activity to
backup.log
#!/bin/bash
# Variables
BACKUP_DIR=~/mongo-backups
TIMESTAMP=$(date +%Y-%m-%d-%H-%M)
DUMP_NAME=dump-$TIMESTAMP
ARCHIVE_NAME=$DUMP_NAME.tar.gz
LOG_FILE=~/mongo-backups/backup.log
# Create backup directory
mkdir -p $BACKUP_DIR
# Dump the database
mongodump --out $BACKUP_DIR/$DUMP_NAME >> $LOG_FILE 2>&1
# Compress the backup
tar -czvf $BACKUP_DIR/$ARCHIVE_NAME -C $BACKUP_DIR $DUMP_NAME >> $LOG_FILE 2>&1
# Upload to Cloudflare R2
aws s3 cp $BACKUP_DIR/$ARCHIVE_NAME s3://mongo-backups/$ARCHIVE_NAME \
--endpoint-url=https://<ACCOUNT_ID>.r2.cloudflarestorage.com \
--profile r2 >> $LOG_FILE 2>&1
# Cleanup dump folder
rm -rf $BACKUP_DIR/$DUMP_NAME
echo "Backup completed at $TIMESTAMP" >> $LOG_FILEMake it executable:
chmod +x ~/backup-mongo.shRun:
bash ~/backup-mongo.shCheck:
- Backup archive exists in
~/mongo-backups backup.loghas timestamped entries- Backup is visible in R2:
aws s3 ls s3://mongo-backups/ \
--endpoint-url=https://<ACCOUNT_ID>.r2.cloudflarestorage.com \
--profile r2To schedule automatic backups every 12 hours:
crontab -eAdd:
0 */12 * * * bash ~/backup-mongo.shAutomated-DB-Backups/
├── backup-mongo.sh # Backup script
├── backup.log # Backup logs
└── README.html # Project documentation (converted to HTML)cd ~
mkdir Automated-DB-Backups
mv ~/backup-mongo.sh ./Automated-DB-Backups/
mv ~/mongo-backups/backup.log ./Automated-DB-Backups/
mv ~/Automated-DB-Backups.html ./Automated-DB-Backups/README.html
cd Automated-DB-Backups
git init
git remote add origin https://github.com/GeigerJR/Automated-DB-Backups.git
git branch -M main
git add .
git commit -m "Initial commit - automated MongoDB backups to R2"
git push -u origin main✅ MongoDB backup runs every 12 hours
✅ Archives stored in mongo-backups folder
✅ Archives uploaded to Cloudflare R2
✅ Logs tracked in backup.log
✅ Project pushed to GitHub