3

I am trying to create a custom container which also contains MongoDB (hence not using the official MongoDB container). I am trying to add authentication to the database, and I think I am having an issue in persisting authentication data, i.e. in dockerfile I run the following command at some point:

RUN (nohup mongod &) && mongo < /data/mongo.js 

and mongo.js is:

use admin
db.createUser(
  {
    user: "admin",
    pwd: "abcd",
    roles: [ "root" ]
  }
)

which yields below during build:

Successfully added user: { "user" : "admin", "roles" : [ "root" ] }
Removing intermediate container...

So after build, when I login to the container and start mongo with --auth flag, still can't login:

# mongo -u admin -p abcd --authenticationDatabase "admin"
MongoDB shell version: 3.2.11
Enter password: 
connecting to: abcd
exception: login failed

What is missing?

1
  • What happens why you try and execute the command manually through docker ? i.e - docker exec -ti your_container sh -c "(nohup mongod &) && mongo < /data/mongo.js" ? not saying this is the solution, lets just check if the command works.
    – rusty009
    Dec 26, 2018 at 21:07

1 Answer 1

1

Instead of writing your own Dockerfile, you can simply pass auth through environment variables to official images, I use compose file something like this:

version: '3.1'

services:
  mongo:
    image: mongo
    restart: always
    container_name: mongo
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: abcd
    ports:
      - "27017:27017"
    volumes: 
      - ./databases:/data/db

  mongo-express:
    image: mongo-express
    restart: always
    container_name: mongo-express
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: abcd

you can have your database persisted in ./databases folder and nice in browser ui at port :8081

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.