| 1 | #!/usr/bin/env bash |
| 2 | |
| 3 | # User-configurable variables |
| 4 | containerName="mongo-db-name" |
| 5 | dbUser="mongo-user" |
| 6 | dbPassword="mongo-password" |
| 7 | dbName="mongo-db" |
| 8 | |
| 9 | hostPort=27017 |
| 10 | containerPort=27017 |
| 11 | |
| 12 | initScriptPath="/tmp/init-mongo.js" |
| 13 | |
| 14 | |
| 15 | # Function to create the init script for mongoDB |
| 16 | create_init_script() { |
| 17 | echo "Creating MongoDB initialization script at $initScriptPath..." |
| 18 | cat <<EOF >"$initScriptPath" |
| 19 | db.createUser({ |
| 20 | user: '$dbUser', |
| 21 | pwd: '$dbPassword', |
| 22 | roles: [{ |
| 23 | role: 'readWrite', |
| 24 | db: '$dbName' |
| 25 | }] |
| 26 | }); |
| 27 | EOF |
| 28 | } |
| 29 | |
| 30 | |
| 31 | # Function to create a new container |
| 32 | create_container() { |
| 33 | echo "Creating container '$containerName'..." |
| 34 | create_init_script |
| 35 | docker run \ |
| 36 | --name "$containerName" \ |
| 37 | -e MONGO_INITDB_DATABASE="$dbName" \ |
| 38 | -v "$initScriptPath:/docker-entrypoint-initdb.d/init-mongo.js" \ |
| 39 | -p "$hostPort:$containerPort" \ |
| 40 | -d mongo |
| 41 | # Remove the init script after starting the container |
| 42 | rm "$initScriptPath" |
| 43 | } |
| 44 | |
| 45 | |
| 46 | # Function to start an existing container |
| 47 | start_container() { |
| 48 | echo "Starting container '$containerName'..." |
| 49 | docker start "$containerName" |
| 50 | } |
| 51 | |
| 52 | |
| 53 | # Main script logic |
| 54 | |
| 55 | # Check whether the container exists (in any state) |
| 56 | containerExists=$(docker ps -a --filter "name=$containerName" --format "{{.Names}}") |
| 57 | |
| 58 | if [ -n "$containerExists" ]; then |
| 59 | # Container exists, check if it's running |
| 60 | containerRunning=$(docker ps --filter "name=$containerName" --filter "status=running" --format "{{.Names}}") |
| 61 | if [ -n "$containerRunning" ]; then |
| 62 | echo "Container '$containerName' is already running." |
| 63 | else |
| 64 | echo "Container '$containerName' exists but is not running." |
| 65 | if ! start_container; then |
| 66 | echo "Failed to start container. Removing and recreating it..." |
| 67 | docker rm "$containerName" |
| 68 | create_container |
| 69 | fi |
| 70 | fi |
| 71 | else |
| 72 | # Container does not exist, create it |
| 73 | create_container |
| 74 | fi |
| 75 |
biscuide / startDockerMongoDB.bash
Last active 2 months ago
Helper script to start/create a docker mongo DB