mongo icon indicating copy to clipboard operation
mongo copied to clipboard

Add an example to documentation for "Initializing a fresh instance"

Open melvingaye opened this issue 1 year ago • 6 comments

Problem

Setting up a user and db (other than the admin user and test db) is a little opaque.

This link How to create a DB for MongoDB container on start up? with over 268K views shows how much of an issue the lack of documentation is. There are many other variations of the search term above, so I'd imagine the numbers would be a lot higher if they were all tallied.

Proposal

Please include something like the below in that section of the documentation

docker-compose.yaml

version: '3.8'

services:
    mongodb:
        image: mongo:latest
        container_name: mongodb
        restart: always
        environment:
            MONGO_INITDB_ROOT_USERNAME: <admin user>
            MONGO_INITDB_ROOT_PASSWORD: <admin password>
            MONGO_INITDB_DATABASE: <custom db>
        ports:
            - 27017:27017
        volumes:
            - ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro

mongo-init.js

print('Init Script - Started Adding the User Roles.');
// use the admin db to create a new user and give that new user permission to the db
// mongo seems to lazy load the db, meaning it'll create the db when a collection is first added
// but the newly created user will still have access to the db
db = db.getSiblingDB('admin');
db.createUser({
  user: '<custom user>',
  pwd: '<custom user password>',
  roles: [{ role: 'readWrite', db: '<custom db>' }],
});
print('Init Script - Ended Adding the User Roles.');
please include the shell version

melvingaye avatar Jan 16 '24 16:01 melvingaye

@melvingaye could you open a PR here: https://github.com/docker-library/docs/blob/master/mongo/content.md

LaurentGoderre avatar May 01 '24 13:05 LaurentGoderre

@melvingaye so its mandatory to do the db.getSibilings()? I don't understand it, if i have to specify the custom db in the script, what's the point to use the MONGO_INITDB_DATABASE environment variable in the first place?

Thanks in advance!

Spucis avatar Aug 30 '24 12:08 Spucis