Skip to content

Instantly share code, notes, and snippets.

@terenty-rezman
Last active November 9, 2021 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save terenty-rezman/db87eccbd337befe8aaab96725581ba1 to your computer and use it in GitHub Desktop.
Save terenty-rezman/db87eccbd337befe8aaab96725581ba1 to your computer and use it in GitHub Desktop.
mongodb dump from running docker container
#!/bin/bash
# dump mongodb from running docker container to specified archive file
# exit on first error
set -e
ARCHIVE_FILE="${2:-mongo_all.db.archive}"
DIR_NAME="$(dirname ${ARCHIVE_FILE})"
# create dir
mkdir -p "${DIR_NAME}"
function print_usage() {
echo -e "\ndump mongodb from specified docker container to specified archive file" >&2
echo -e "\nUsage: $0 [docker_container_with_mongodb]" >&2
echo -e " $0 [docker_container_with_mongodb] [dump_to_file] \n" >&2
echo -e "Example:" >&2
echo -e " $0 fa092afe870 mongo_dump/mongo_all.db.archive \n" >&2
}
if [[ "$#" -lt 1 || "$#" -gt 2 ]]; then
echo "ERROR: wrong number of args!" >&2
print_usage
exit 1
fi
# taken from https://davejansen.com/how-to-dump-restore-a-mongodb-database-from-a-docker-container/
# create dump dir inside container
docker exec -i "${1}" mkdir -p "${DIR_NAME}"
# do the dump
docker exec -i "${1}" /usr/bin/mongodump --archive="${ARCHIVE_FILE}"
# copy to host
docker cp "${1}":${ARCHIVE_FILE} ${ARCHIVE_FILE}
echo dumped to "${ARCHIVE_FILE}"
#!/bin/bash
# restore mongodb running in specified docker container from specified archive file
# exit on first error
set -e
ARCHIVE_FILE="${2:-mongo_all.db.archive}"
DIR_NAME="$(dirname ${ARCHIVE_FILE})"
function print_usage() {
echo -e "\nrestore mongodb running in specified docker container from specified archive file" >&2
echo -e "\nUsage: $0 [docker_container_with_mongodb]" >&2
echo -e " $0 [docker_container_with_mongodb] [restore_from_file] \n" >&2
echo -e "Example:" >&2
echo -e " $0 fa092afe870 mongo_dump/mongo_all.db.archive \n" >&2
}
if [[ "$#" -lt 1 || "$#" -gt 2 ]]; then
echo "ERROR: wrong number of args!" >&2
print_usage
exit 1
fi
read -p "Are you sure you want to restore mongodb running in container ${1} from archive ${ARCHIVE_FILE}? (y/N) " decision
if [ "$decision" != "Y" ] && [ "$decision" != "y" ]; then
echo canceled
exit
fi
# based on https://davejansen.com/how-to-dump-restore-a-mongodb-database-from-a-docker-container/
# create dump dir inside container
docker exec -i "${1}" mkdir -p "${DIR_NAME}"
# copy dump archive to container
docker cp "${ARCHIVE_FILE}" "${1}":"${ARCHIVE_FILE}"
# restore mongodb
docker exec -i "${1}" /usr/bin/mongorestore --archive="${ARCHIVE_FILE}"
echo mongodb in container "${1}" restored from "${ARCHIVE_FILE}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment