Mongodb user created with docker-entrypoint-initdb.d doesn't persist in the database

Viewed 478

I've been trying to create a user (who is not the administrator) for my database but I can't get it to persist in the database.

I'm using a sh init script from the docker-entrypoint-initdb.d entry point. When I run docker-compose up everything seems to be working. But when I try to connect and search for the user it doesn't appear.

The log shows:

UserNotFound: Could not find user \"john\" for db \"datadb\"

The structure of my project is really simple:

enter image description here

docker-compose.yml

version: '3.3'
services:
  mongodb:
    image: mongo:latest
    container_name: mongo_db
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: rootpass
      MONGO_INITDB_DATABASE: datadb
    volumes:
      - ./init.d/:/docker-entrypoint-initdb.d/
      - mongodbdata:/data/db
    restart: always
volumes:
  mongodbdata:
    driver: local

init-mongo.sh

#!/bin/bash
set -eu
mongo -u $MONGO_INITDB_ROOT_USERNAME -p $MONGO_INITDB_ROOT_PASSWORD <<EOF
    db = db.getSiblingDB('$MONGO_INITDB_DATABASE');
    use '$MONGO_INITDB_DATABASE';
    db.createUser({
        user: 'john', 
        pwd: '12345', 
        roles: [{
            role: 'readWrite', 
            db: '$MONGO_INITDB_DATABASE'
        }]
    });
EOF

Is there anything I'm missing?

1 Answers

If add show users after createUser in init-mongo.sh, you will find next in docker-compose logs:

mongo_db   | {
mongo_db   |    "_id" : "'datadb'.john",
mongo_db   |    "userId" : UUID("92abb590-3d2a-44d1-bde4-58b3b3acd1d8"),
mongo_db   |    "user" : "john",
mongo_db   |    "db" : "'datadb'",
mongo_db   |    "roles" : [
mongo_db   |            {
mongo_db   |                    "role" : "readWrite",
mongo_db   |                    "db" : "datadb"
mongo_db   |            }
mongo_db   |    ],
mongo_db   |    "mechanisms" : [
mongo_db   |            "SCRAM-SHA-1",
mongo_db   |            "SCRAM-SHA-256"
mongo_db   |    ]
mongo_db   | }

You could see it becomes "'datadb'.john", not "datadb.john", that means the database name now is 'datadb', not datadb. So should change next line in init-mongo.sh, not use '$MONGO_INITDB_DATABASE';, but next:

use $MONGO_INITDB_DATABASE;

Then, docker-compose down -v(Add -v to remove the volume, so the database will init again when up, with which you could see the effect), and docker-compose up -d, finally check it:

> use datadb;
switched to db datadb
> show users;
{
        "_id" : "datadb.john",
        "userId" : UUID("0e643984-48f9-4da4-a3ea-0e7159240724"),
        "user" : "john",
        "db" : "datadb",
        "roles" : [
                {
                        "role" : "readWrite",
                        "db" : "datadb"
                }
        ],
        "mechanisms" : [
                "SCRAM-SHA-1",
                "SCRAM-SHA-256"
        ]
}
Related