This is a script to run mongodump in a running MongoDB container, and backup to the local server as a tgz file.
1.) Runs mongodump
2.) Creates a tgz file where the script is ran
3.) Removes any old tgz files that are in the same directory
// My MongoDB is container is running in Docker Swarm mode to use Docker Secrets.
#!/bin/bash
set -euo pipefail
# Create a temp directory for the backup
TMPDIR="$(mktemp -d)"
trap "rm -rf $TMPDIR" EXIT
# Get the running MongoDB container ID
CONTAINER_ID=$(docker ps --filter "name=btc_mongodb" --format "{{.ID}}" | head -n 1)
if [ -z "$CONTAINER_ID" ]; then
echo "No running container found with 'btc_mongodb' in its name."
exit 1
fi
# Retrieve MongoDB credentials from secrets in the container
USERNAME=$(docker exec "$CONTAINER_ID" cat /run/secrets/mongo_root_username)
PASSWORD=$(docker exec "$CONTAINER_ID" cat /run/secrets/mongo_root_password)
# Run mongodump inside the container, outputting to /tmp
docker exec "$CONTAINER_ID" mongodump \
--uri="mongodb://$USERNAME:$PASSWORD@localhost:27017/" \
--out /tmp/mongodump
# Copy the mongodump from the container to the host's temp directory
docker cp "$CONTAINER_ID":/tmp/mongodump "$TMPDIR"
# Create the archive in the current directory
BACKUP_FILENAME="$(date +%Y-%m%d-%H%M)-btcMongo.tgz"
tar -czf "$BACKUP_FILENAME" -C "$TMPDIR/mongodump" .
# Remove any previous *-btcMongo.tgz except the newly created one
for f in *-btcMongo.tgz; do
if [[ "$f" != "$BACKUP_FILENAME" ]]; then
rm -f -- "$f"
fi
done
echo "Backup complete: $BACKUP_FILENAME"