Last active 1742658617

Helper script to start/create a docker mongo DB

Revision 62fa18e4dea8d31798a96206181bf13407608625

startDockerMongoDB.bash Raw
1#!/usr/bin/env bash
2
3# User-configurable variables
4containerName="mongo-db-name"
5dbUser="mongo-user"
6dbPassword="mongo-password"
7dbName="mongo-db"
8
9hostPort=27017
10containerPort=27017
11
12initScriptPath="/tmp/init-mongo.js"
13
14
15# Function to create the init script for mongoDB
16create_init_script() {
17 echo "Creating MongoDB initialization script at $initScriptPath..."
18 cat <<EOF >"$initScriptPath"
19db.createUser({
20 user: '$dbUser',
21 pwd: '$dbPassword',
22 roles: [{
23 role: 'readWrite',
24 db: '$dbName'
25 }]
26});
27EOF
28}
29
30
31# Function to create a new container
32create_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
47start_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)
56containerExists=$(docker ps -a --filter "name=$containerName" --format "{{.Names}}")
57
58if [ -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
71else
72 # Container does not exist, create it
73 create_container
74fi
75