Search code examples
mongodbdockerdocker-composedockerfilemongo-shell

Creating a user for a non existing database not working


I am trying to deploy a MongoDB database in a docker container. This database is then used by a node js server.

When I start the mongo container, it first executes a shell script that works because I can see it log the error code 1 which means the request was successfully. Here is the file:

mongo -- "$MONGO_INITDB_DATABASE" <<EOF
    var rootUser = '$MONGO_INITDB_ROOT_USERNAME';
    var rootPassword = '$MONGO_INITDB_ROOT_PASSWORD';
    var user = '$MONGO_INITDB_USERNAME';
    var passwd = '$MONGO_INITDB_USERNAME';
    var admin = db.getSiblingDB('admin');
    admin.auth(rootUser, rootPassword);
    db.createUser({user: user, pwd: passwd, roles: [{role:"readWrite",db:"$MONGO_INITDB_DATABASE"]});
EOF

But after this is done and I try to connect to the database with the nodejs server, it outputs that login failed with the user that is supposed to be created.
To go further in my research, I then entered the MongoDB container to execute the same script. This is how I did it:

use admin #To log in as admin
db.auth({user: root, PWD: rootPwd})
use mydatabase
db.createUser({user: user, PWD: passwd, roles:[{role:"readWrite",db:"myDatabase"]});

I then see that my nodejs has no problem accessing the database.
I don't know what I am doing wrong since everything seems working.

I have actually realised that I get this error message :

 Error saving history file: FileOpenFailed: Unable to open() file /home/mongodb/.dbshell: Unknown error

But I also get it when my root user is created and since my root user is working, I don't think this is the problem.

EDIT
Here is the Dockerfile:

FROM node: latest

WORKDIR /opt/app

COPY app .
COPY .env ./

RUN npm i

EXPOSE 3000

CMD npm run start:prod

And Here is the docker-compose file:

version: '3.7'

services:
  mongo:
    container_name: mongo
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: ${MONGO_INITDB_ROOT_USERNAME}
      MONGO_INITDB_ROOT_PASSWORD: ${MONGO_INITDB_ROOT_PASSWORD}
      MONGO_INITDB_DATABASE: ${MONGO_INITDB_DATABASE}
      MONGO_INITDB_USERNAME: ${MONGO_INITDB_USERNAME}
      MONGO_INITDB_PASSWORD: ${MONGO_INITDB_PASSWORD}
    volumes:
      - /data:/data/db
      - ./init-mongo.sh:/docker-entrypoint-initdb.d/init-mongo.sh
  api:
    container_name: api
    build:
     context: .
     dockerfile: Dockerfile.production
    image: api
    depends_on:
     - mongo
    restart: always
    ports:
      - 3000:3000

Solution

  • var passwd = '$MONGO_INITDB_USERNAME';

    Are you setting the correct password here? (It's using the $USERNAME variable rather than the password one)