Docker Persisting Data During Build 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 &amp;) &amp;&amp; mongo &lt; /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?
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