Skip to content

Instantly share code, notes, and snippets.

@rbcmgs
Last active May 3, 2024 03:57
Show Gist options
  • Save rbcmgs/4b3f7b2d23a070f2577e756e60a76531 to your computer and use it in GitHub Desktop.
Save rbcmgs/4b3f7b2d23a070f2577e756e60a76531 to your computer and use it in GitHub Desktop.
A Bash script to automate the setup of MongoDB within a Docker container on systems supporting Docker. This script handles the creation of a data directory, pulling the MongoDB image from Docker Hub, and running the MongoDB container. It supports optional command-line input to configure the container for either local-only or external network con…
#!/bin/bash
# Usage:
# - Without arguments: Follow prompts during execution.
# - With arguments: Specify `local` for local-only access or `external` for external access.
# Example: sudo ./setup-mongodb-container.sh local
# Alert user about the root privileges requirement.
if [ "$(id -u)" -ne 0 ]; then
echo "This script must be run with sudo or as root."
exit 1
fi
# Create a directory on the host to store the MongoDB data securely.
sudo mkdir -p /opt/mongodb/data
# Retrieve the latest stable MongoDB image.
sudo docker pull mongo:latest
# Define initial port mapping for local access.
PORT_MAPPING="127.0.0.1:27017:27017"
# Check if access level is specified as a command-line argument.
if [ -n "$1" ]; then
if [ "$1" == "external" ]; then
PORT_MAPPING="27017:27017"
fi
else
# Ask user if MongoDB should be accessible externally.
echo "Allow external connections to MongoDB? (yes/no)"
read EXTERNAL_ACCESS
if [ "$EXTERNAL_ACCESS" == "yes" ]; then
PORT_MAPPING="27017:27017"
fi
fi
# Run the MongoDB container with the configured port mapping.
sudo docker run -d \
--restart unless-stopped \
--name mongodb-container \
-v /opt/mongodb/data:/data/db \
-p $PORT_MAPPING \
mongo:latest
# Verify the container is running.
sudo docker ps -a
# Output connection and configuration details to the user.
echo "MongoDB installed and running in a Docker container:"
if [[ "$PORT_MAPPING" == *"127.0.0.1"* ]]; then
echo "Accessible only on localhost (127.0.0.1)"
else
echo "Accessible on local and external network interfaces"
fi
echo "Port: 27017"
echo "Data Directory: /opt/mongodb/data"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment