Skip to content

Instantly share code, notes, and snippets.

@carpincho
Forked from maitrungduc1410/.env
Created August 21, 2024 21:30
Show Gist options
  • Save carpincho/d4938b098eaa2048e890622114c53a10 to your computer and use it in GitHub Desktop.
Save carpincho/d4938b098eaa2048e890622114c53a10 to your computer and use it in GitHub Desktop.
Docker compose HEALTHCHECK for MongoDB with authentication (Mongo V4,5,6 supported)
DB_HOST=db
DB_PORT=27017
DB_ROOT_USER=root
DB_ROOT_PASS=rootpass
DB_USER=user
DB_PASSWORD=userpass
DB_NAME=mydb
echo 'Creating application user and db'
mongo ${DB_NAME} \
--host localhost \
--port ${DB_PORT} \
-u ${MONGO_INITDB_ROOT_USERNAME} \
-p ${MONGO_INITDB_ROOT_PASSWORD} \
--authenticationDatabase admin \
--eval "db.createUser({user: '${DB_USER}', pwd: '${DB_PASSWORD}', roles:[{role:'dbOwner', db: '${DB_NAME}'}]});"
version: "3.5"
services:
db:
image: mongo:4
volumes:
- ./db-entrypoint.sh:/docker-entrypoint-initdb.d/db-entrypoint.sh
restart: always
healthcheck:
test: echo 'db.runCommand("ping").ok' | mongo mongodb://${DB_USER}:${DB_PASSWORD}@localhost:${DB_PORT}/?authSource=${DB_NAME} --quiet
interval: 30s
timeout: 10s
retries: 5
environment:
- MONGO_INITDB_ROOT_USERNAME=${DB_ROOT_USER}
- MONGO_INITDB_ROOT_PASSWORD=${DB_ROOT_PASS}
- DB_PORT=${DB_PORT}
- DB_NAME=${DB_NAME}
- DB_USER=${DB_USER}
- DB_PASSWORD=${DB_PASSWORD}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment