There are different MongoDB Backup Methods available for MongoDB 2.6. For our small development Instances we will create a Backup with mongodump which is "simple and efficient for backing up small MongoDB deployments". A real nice thing about this approach is that the tools mongodump and mongorestore "can operate against a running mongod process". This backup method can "adversely affect mongod performance" which is no real issue in our Planets development scenario.
Backup
Basically we follow the instructions Back Up and Restore with MongoDB Tools.
But since our MongoDB is running inside a container we may want an additional step to get the data to our local hard drive.
First we create a backup with mongodump of our database planets
inside the container in the directory /data/backup
:
$ docker exec -it mongodb-planets mongodump --out /data/planets-backup-$(date +'%Y%m%d%H%M%S') --db planets
We can quickly check the results:
$ docker exec -it mongodb-planets ls -lrt /data
....
drwxr-xr-x 3 root root 4096 Aug 31 08:34 planets-backup-20160831103407
And grab the backup file(s):
$ docker cp mongodb-planets:/data/planets-backup-20160831103407 /tmp
As this might be useful for other project in the future we ended up with this small backup-local-mongodb.sh
script:
#!/bin/sh
export DATABASE_NAME="planets"
export TIMESTAMP=$(date +'%Y%m%d%H%M%S')
docker exec -t mongodb-${DATABASE_NAME} mongodump --out /data/${DATABASE_NAME}-backup-${TIMESTAMP} --db ${DATABASE_NAME}
docker cp mongodb-${DATABASE_NAME}:/data/${DATABASE_NAME}-backup-${TIMESTAMP} .
Note: To use this script in your /etc/crontab
for example you have to remove the i
(interactive) flag from the Docker command.
That's the backup part.
Restore
As during the backup we basically follow the instructions Restore a Database with mongorestore
If we want to restore the backup with mongorestore into another container we first copy the dump we want to use into that container:
$ docker cp /tmp/planets-backup-20160831103407 mongodb-planets:/data
Then run the restore command inside the container:
$ docker exec -it mongodb-planets mongorestore /data/planets-backup-20160831103407
Back in time.
Bonus
Note: One-liner using
--archive
for MongoDB backups with 3.2.x and later:
$ docker exec mongodb mongodump --archive > dump-$(date +'%Y%m%d%H%M%S')