Skip to content

Instantly share code, notes, and snippets.

@IdrisAkintobi
Created March 26, 2025 10:48
Show Gist options
  • Save IdrisAkintobi/3af0d59ab629a6898a768a7f51bfa397 to your computer and use it in GitHub Desktop.
Save IdrisAkintobi/3af0d59ab629a6898a768a7f51bfa397 to your computer and use it in GitHub Desktop.
Mongo-Docker - Single replica instance
services:
mongo:
container_name: "mongo-container"
entrypoint: >
/bin/bash -c '
mkdir /data/keys | true &&
openssl rand -base64 756 > /data/keys/keyfile.key &&
chmod 400 /data/keys/keyfile.key &&
chown mongodb:mongodb /data/keys/keyfile.key &&
/usr/local/bin/docker-entrypoint.sh mongod --replSet rs0 --keyFile /data/keys/keyfile.key --bind_ip_all'
image: "mongo:8.0"
ports:
- 27017:27017
environment:
MONGO_INITDB_ROOT_USERNAME: ${MONGO_USERNAME}
MONGO_INITDB_ROOT_PASSWORD: ${MONGO_PASSWORD}
MONGO_INITDB_DATABASE: ${MONGO_DATABASE}
volumes:
- "mongo-data:/data"
healthcheck:
test: >
mongosh
-u $${MONGO_INITDB_ROOT_USERNAME}
-p $${MONGO_INITDB_ROOT_PASSWORD}
--eval "
try {
rs.status()
} catch (err) {
rs.initiate({ _id: 'rs0', members: [ { _id: 0, host: '127.0.0.1:27017' } ] })
}
" | mongosh --port 27017 --quiet
interval: 5s
timeout: 30s
start_period: 0s
start_interval: 1s
retries: 30
restart: unless-stopped
volumes:
mongo-data:
MONGO_USERNAME=root
MONGO_PASSWORD=secret
MONGO_DATABASE=app_db
# Load environment variables from .env
include .env
export $(shell sed 's/=.*//' .env)
# Variables
CONTAINER_NAME = mongo-container
# Build the Docker images (optional, as you're using a pre-built image)
build:
docker compose up --build -d
# Start the Docker Compose services
up:
docker compose up -d
# Check logs for the Mongo service
logs:
docker compose logs --tail 50
# Connect to the mongo shell
connect:
docker exec -it $(CONTAINER_NAME) mongosh -u $(MONGO_USERNAME) -p $(MONGO_PASSWORD)
# Stop the Docker Compose services
down:
docker compose down
# Stop and remove the Docker Compose services, along with volumes
clean:
docker compose down -v
# Restart the Docker Compose services
restart:
docker compose restart
# Show the status of the services
ps:
docker compose ps -a
# Help message to display available targets
help:
@echo "Available targets:"
@echo " build - Build the Docker images"
@echo " up - Start the services defined in docker-compose.yml"
@echo " down - Stop the services"
@echo " clean - Stop and remove the services, along with volumes"
@echo " logs - View logs for the Mongo service"
@echo " restart - Restart the Docker services"
@echo " ps - View the status of all services"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment