0

I have a locally running mongo docker container. However I cannot connect to it for some reason. It says I can connect and the port is correct etc but the authorization is wrong.

Docker

FROM mongo:4.4.1

COPY ./mongo-localhost-init.sh /docker-entrypoint-initdb.d/

mongo-localhost-auth.env

MONGO_INITDB_ROOT_USERNAME=root
MONGO_INITDB_ROOT_PASSWORD=password
MONGO_INITDB_DATABASE=admin
dbUserWebsite=username
dbPwdWebsite=password

mongo-localhost-init.sh

#!/bin/bash
set -e

# dbUser is the username used from application code to interact with databases and dbPwd is the password for this user.
# MONGO_INITDB_ROOT_USERNAME & MONGO_INITDB_ROOT_PASSWORD is the config for db admin.
# admin user is expected to be already created when this script executes. We use it here to authenticate as admin to create
# dbUser and databases.

echo ">>>>>>> trying to create database and users"
if [ -n "${MONGO_INITDB_ROOT_USERNAME:-}" ] && [ -n "${MONGO_INITDB_ROOT_PASSWORD:-}" ] && [ -n "${dbUserWebsite:-}" ] && [ -n "${dbPwdWebsite:-}" ]; then
mongo -u $MONGO_INITDB_ROOT_USERNAME -p $MONGO_INITDB_ROOT_PASSWORD<<EOF
db=db.getSiblingDB('website');
use website;
db.users.createIndex( { email: 1 }, { unique: true } )
db.createUser({
  user:  '$dbUserWebsite',
  pwd: '$dbPwdWebsite',
  roles: [{
    role: 'readWrite',
    db: 'website'
  }]
});
EOF
else
    echo "MONGO_INITDB_ROOT_USERNAME,MONGO_INITDB_ROOT_PASSWORD,dbUserWebsite,dbPwdWebsite must be provided. Some of these are missing, hence exiting database and user creation"
    exit 403
fi

I ensured to remove all images and containers and try again from scratch:

docker rmi {id or name} -f
docker kill {id}

Then built the image:

// build docker image
docker build  -f Dockerfile -t mongo-localhost .

//run the image
docker container run --env-file mongo-localhost-auth.env --publish 27017:27017 -d mongo-localhost 

I try to connect via:

localhost:27017 and with the correct db name, username and password.

It says connected to localhost:27017 but authorization failed.

All I can really see in the docker logs are:

Error saving history file: FileOpenFailed Unable to open() file /home/mongodb/.dbshell: No such file or directory

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.