Skip to content

Commit fca3f5a

Browse files
committed
Add MongoDB backup script with service check
1 parent 2afb17c commit fca3f5a

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,16 @@ python src/run.py --help
3030
```
3131

3232
for a description of all available options.
33+
34+
## MongoDB backup script
35+
36+
`scripts/backup_mongodb.sh` dumps a MongoDB database to a Dropbox-synced
37+
folder. The script starts `mongod` if it is not running and stops it again
38+
when the backup finishes (if it was started by the script).
39+
40+
Make it executable before scheduling it with `cron`:
41+
42+
```bash
43+
chmod +x scripts/backup_mongodb.sh
44+
```
45+

scripts/backup_mongodb.sh

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#!/bin/bash
2+
# scripts/backup_mongodb.sh
3+
# Backup MongoDB database, ensuring mongod is running.
4+
5+
DATE=$(date +%Y-%m-%d)
6+
BACKUP_DIR="$HOME/Dropbox/backups"
7+
DBNAME="DBNAME"
8+
USERNAME="USERNAME"
9+
PASSWORD="PASSWORD"
10+
BACKUP_PATH="$BACKUP_DIR/db_backup_${DATE}"
11+
12+
mkdir -p "$BACKUP_DIR"
13+
14+
# Track whether we started mongod
15+
started_mongod=false
16+
17+
# Check if mongod process is running
18+
if pgrep mongod >/dev/null; then
19+
echo "mongod is running"
20+
else
21+
echo "mongod is not running. Starting..."
22+
if command -v systemctl >/dev/null; then
23+
sudo systemctl start mongod
24+
else
25+
sudo service mongod start
26+
fi
27+
started_mongod=true
28+
fi
29+
30+
# Dump the database
31+
mongodump --db "$DBNAME" --username "$USERNAME" --password "$PASSWORD" --out "$BACKUP_PATH"
32+
33+
# Stop mongod if we started it
34+
if [ "$started_mongod" = true ]; then
35+
echo "Stopping mongod..."
36+
if command -v systemctl >/dev/null; then
37+
sudo systemctl stop mongod
38+
else
39+
sudo service mongod stop
40+
fi
41+
fi

0 commit comments

Comments
 (0)