Skip to content

Instantly share code, notes, and snippets.

@gioragutt
Last active February 7, 2018 16:20
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 gioragutt/902320e568fc6e2293971e4a1c8e1bdc to your computer and use it in GitHub Desktop.
Save gioragutt/902320e568fc6e2293971e4a1c8e1bdc to your computer and use it in GitHub Desktop.
initialize mongo with replication set
DEFAULT_VOLUME_PATH=~/mongo/data
CONTAINER_NAME=some-mongo
runMongoContainer()
{
VOLUME=$1
docker run --name $CONTAINER_NAME -v $VOLUME:/data/bs -p 27017:27017 -d mongo --replSet rs0
####################################################################### NOTICE --replSet
}
executeCommandOnShell()
{
docker exec -it $CONTAINER_NAME mongo admin --eval "$1"
}
notifyImageDownloading()
{
if [ -z $(docker images -q mongo) ]; then
echo ""
echo "Mongo image not yet installed, will install now..."
echo "This might take a few minutes!"
echo ""
fi
}
main()
{
VOLUME_PATH=$DEFAULT_VOLUME_PATH
if [[ $# -gt 0 ]]; then VOLUME_PATH=$1; fi
echo ""
echo "--- Running mongo container ---"
notifyImageDownloading
echo ""
runMongoContainer $VOLUME_PATH
sleep 1s
echo "--- Initiating replication set ---"
echo ""
executeCommandOnShell "rs.initiate()"
######################## Initialize replica set
sleep 2s
echo "--- Creating admin user ---"
echo ""
executeCommandOnShell "db.createUser({user: 'root', pwd: 'root', roles: [{role: 'userAdminAnyDatabase', db: 'admin'}]})" # IMPORTANT
##################### Create a user
echo ""
echo "You're good to go!"
echo "Make sure you .env file has the following settings set:"
echo "DATABASE_URL=mongodb://root:root@localhost:27017/"
echo "DATABASE_NAME=admin"
}
if [ "$1" == "--help" ]; then
echo ""
echo "Usage: bootstrap.sh <optional path for volume>"
echo ""
echo "Default volume path is: '$DEFAULT_VOLUME_PATH'"
echo ""
echo "Stop/start container:"
echo " docker stop/start $CONTAINER_NAME"
echo ""
echo "Delete the container:"
echo " docker rm $CONTAINER_NAME"
exit 0
fi
main $@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment