0
votes

how would you script the Dockerfile to create admin user for mongoDB 4.2 ?

Is there a one line command to create admin users not using an interactive subshell ? (didn't see any in mongoDB documentation)

Thanks for your help.

Passing MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD does not work anymore (removed from Docker hub mongo image documentation).

The mongo Docker hub documentation only shows interactive shell admin user creation.

> mongo admin

executes mongo interactive shell but how do you write a shell script to enter commands in that subshell from the top level shell ?

FROM mongo

RUN mongo admin ???? db.createUser({ user: 'jsmith', pwd: 'some-initial-password', roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] });

The docker build process should display:

Successfully added user: { "user" : "jsmith", "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }

1

1 Answers

0
votes

OK, here's the way to add authetication via the Dockerfile.

  • create a init.js file:
db = new Mongo().getDB("admin");

// create admin user

db.createUser({
  user: "admin",
  pwd: "password",
  roles: [
    {
      role: "clusterAdmin",
      db: "admin"
    }
  ]
});


// create non admin user

db.createUser({
  user: "toto",
  pwd: "123",
  roles: [
    {
      role: "readWrite",
      db: "tube"
    }
  ]
});


  • create the Dockerfile:
FROM mongo

# init.js will be executed when the mongo instance runs

COPY ./init.js ./docker-entrypoint-initdb.d
  • build your docker image

docker build -t mongoAuth .

  • run the container (attached mode to see the logs)

docker run --name mongoContainer -p 27017:27017 mongoAuth

What I was missing was that I didn't set the database on which to create the users (admin database) by using:

db = new Mongo().getDB("admin");