Skip to content

Instantly share code, notes, and snippets.

@andiMenge
Last active February 6, 2020 16:30
Show Gist options
  • Select an option

  • Save andiMenge/d51fccb8ceb6ee502168c3ec97d80252 to your computer and use it in GitHub Desktop.

Select an option

Save andiMenge/d51fccb8ceb6ee502168c3ec97d80252 to your computer and use it in GitHub Desktop.
Some Database stuff

Mongodb

Backup and restore

  • If target container is not in the default network the argument --network <my-docker-network-name> has to be used with docker command.

Backup

docker run --rm --init --user 0 -v ${PWD}:/backups --link <mongodb-container-id>:src-mongodb mongo:4-xenial /bin/bash -c 'mongodump -h src-mongodb:27017 --db movie-favs --gzip --archive=/backups/$(date +"%d-%m-%Y")-mongodb.archive.gz'

Restore

  • To overwrite existing entries the agument --drop has to be used with mongorestore command.
docker run --rm --init --user 0 -v ${PWD}:/restores --link <mongodb-container-id>:dst-mongodb mongo:4-xenial /bin/bash -c 'mongorestore -h dst-mongodb:27017 --gzip --archive=/restores/$(date +"%d-%m-%Y")-mongodb.archive.gz'

Backup script

#!/bin/bash

# General Config
mongoImage="mongo:4-xenial"
currentDate=$(date +"%d-%m-%Y")

# Backup Job config
backupFolder="/my-folder/backups/"
logmsg="..database backup done!"
mongodbDockerNetwork="movie-recommendations-backend_default"
mongodbHost="mongodb" # The logical hostname of the mongodb container
mongodbDatabase="my-database"

# No touchy touchy
backupCmd="mongodump -h ${mongodbHost}:27017 --db $mongodbDatabase --gzip --archive=/backups/${currentDate}-mongodb.archive.gz"


function backup(){
  docker run --rm --init --user 0 -v ${backupFolder}:/backups --network $mongodbDockerNetwork $mongoImage /bin/bash -c "$backupCmd" && /usr/bin/logger $logmsg
}

function cleanBackups(){
  /usr/bin/logger "removing old backups"
  /usr/bin/find $backupFolder -mtime +7 -type f -delete
}

backup
cleanBackups

MongoDB Script for DB cloning

mongo --nodb /clone.js

// This DB will be droped
const targetDB = {
  host: '',
  user: '',
  password: '',
  dbName: ''
};

const sourceDB = {
  host: '',
  user: '',
  password: '',
  dbName: ''
};

// Connect to db
db = connect(targetDB.host);
db.auth(targetDB.user, targetDB.password);

// Drop the database
printjson(db.dropDatabase());

// Copy
printjson(
  db.copyDatabase(
    sourceDB.dbName,
    targetDB.dbName,
    sourceDB.host,
    sourceDB.user,
    sourceDB.password
  )
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment