Create a new user for MongoDB inside Docker

My solution:

Inside your Dockerfile:

ADD create_ddbb.js /tmp/

RUN mongod -f /etc/mongod.conf --fork --logpath /var/log/mongodb.log \
    && sleep 5 \
    && mongo <YOUR DATABASE> /tmp/create_ddbb.js

Inside the create_ddbb.js:

db.createUser(
    {
      user: "your_user",
      pwd: "********************",
      roles: [
         { role: "dbOwner", db: "your_database" }
      ]
    }
,
    {
        w: "majority",
        wtimeout: 5000
    }
);
db.createCollection("test");

The createColleciton("test") at the end is extremely important. Without that, the createUser isn't applied. I don't know why exactly, sorry.

Tags:

Docker

Mongodb