kyapwc
kyapwc

Reputation: 398

How to initialize a new user and database for mongodb on docker-compose

So, currently I have a docker-compose.yml file that has the following:

version: "2"
services:
 pastime:
   build:
     context: ./pastime
     dockerfile: ./Dockerfile
   volumes:
     - ./pastime:/usr/src/app
     - /usr/src/app/node_modules
   ports:
     - "3000:3000"
   depends_on:
     - mongo
   environment:
     - PORT=3000
     - DATABASE_USER=pastime
     - DATABASE_URL=mongo:27017
     - DATABASE_PASS=pastime123
     - DATABASE_NAME=pastime
   command: npm run start:dev
 mongo:
   image: mongo:latest
   restart: always
   ports:
     - "27017:27017"
   environment:
     - MONGO_INITDB_DATABASE=pastime
     - MONGO_INITDB_ROOT_USERNAME=root
     - MONGO_INITDB_ROOT_PASSWORD=root_password
   volumes:
     - ./init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro

And also my init-mongo.js file has:

db.createUser({
  user: 'pastime',
  pwd: 'pastime123',
  roles: [
    {
      role: 'readWrite',
      db: 'pastime'
    }
  ]
})

I am not sure why, but the output I get everytime when I do a docker-compose logs -f mongo comes up to: SASL SCRAM-SHA-1 authentication failed for pastime on admin from client 172.19.0.3:55568 ; UserNotFound: Could not find user "pastime"...

I suspect that the init script is not running as I don't see kinds of logs about it in my mongo container.

Have followed a few examples, mainly following thru with this one: How to create a DB for MongoDB container on start up?

Upvotes: 9

Views: 17891

Answers (2)

LaTouwne
LaTouwne

Reputation: 234

There is some correspondence with a couple of posts through Stack Overflow - I think this one is of interest and adds some insights in a very comprehensive way: https://stackoverflow.com/a/53522699/13232069

The emphasis is on the need to log on admin before creating a new user. In addition to a docker-compose.yml file, it would then look like (with a shell script - all credit goes to x-yuri):

init-mongo.sh:

mongo -- "$MONGO_INITDB_DATABASE" <<EOF
    var rootUser = '$MONGO_INITDB_ROOT_USERNAME';
    var rootPassword = '$MONGO_INITDB_ROOT_PASSWORD';
    var admin = db.getSiblingDB('admin');
    admin.auth(rootUser, rootPassword);

    var user = '$MONGO_INITDB_USERNAME';
    var passwd = '$(cat "$MONGO_INITDB_PASSWORD_FILE")';
    db.createUser({user: user, pwd: passwd, roles: ["readWrite"]});
EOF

or with a mongo-init.js file :

db = db.getSiblingDB('admin');
// move to the admin db - always created in Mongo
db.auth("rootUser", "rootPassword");
// log as root admin if you decided to authenticate in your docker-compose file...
db = db.getSiblingDB('DB_test');
// create and move to your new database
db.createUser({
'user': "dbUser",
'pwd': "dbPwd",
'roles': [{
    'role': 'dbOwner',
    'db': 'DB_test'}]});
// user created
db.createCollection('collection_test');
// add new collection

That insight definitely unlocked me !

Upvotes: 3

leeman24
leeman24

Reputation: 2899

The configuration you have posted above should work. I suspect that you may of started your containers prior to mounting the init-mongo.js under /docker-entrypoint-initdb.d/init-mongo.js which is the result of the error.

Since you are not mounting a data volume for mongodb, you can simply just destroy and restart your containers using:

docker-compose down
docker-compose up -d
docker-compose logs -f

I actually was curious so copied your config and tested it successfully. See snippet from docker-compose logs -f:

mongo_1  | 2019-09-06T15:43:19.982+0000 I  NETWORK  [conn3] received client metadata from 127.0.0.1:46874 conn3: { application: { name: "MongoDB Shell" }, driver: { name: "MongoDB Internal Client", version: "4.2.0" }, os: { type: "Linux", name: "Ubuntu", architecture: "x86_64", version: "18.04" } }
mongo_1  | Successfully added user: {
mongo_1  |  "user" : "pastime",
mongo_1  |  "roles" : [
mongo_1  |      {
mongo_1  |          "role" : "readWrite",
mongo_1  |          "db" : "pastime"
mongo_1  |      }
mongo_1  |  ]
mongo_1  | }

I was able to exec into the container and connect to the db with that user:

$ docker-compose exec mongo bash
root@62ec89743bc0:/# mongo --username pastime --password pastime123 --authenticationDatabase pastime
MongoDB shell version v4.2.0
connecting to: mongodb://127.0.0.1:27017/?authSource=pastime&compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("313dd5a9-c417-42c2-b35e-27b301e82def") }
MongoDB server version: 4.2.0
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
    http://docs.mongodb.org/
Questions? Try the support group
    http://groups.google.com/group/mongodb-user
> use pastime
switched to db pastime
>
$ cat docker-compose.yml
version: "2"
services:
  mongo:
    image: mongo:latest
    restart: always
    ports:
      - "27017:27017"
    environment:
      - MONGO_INITDB_DATABASE=pastime
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=root_password
    volumes:
      - ./init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro

$ cat init-mongo.js
db.createUser({
  user: 'pastime',
  pwd: 'pastime123',
  roles: [
    {
      role: 'readWrite',
      db: 'pastime'
    }
  ]
})

Upvotes: 7

Related Questions