0

I try to connect to docker MongoDB from a NestJS API but, got after hours the following error :

ERROR [MongooseModule] Unable to connect to the database

I checked some posts :

Here is my docker-compose.yml :

version: '3.7'
services: 
  mongo5:
    container_name: mongo5-user-dev
    image: mongo:5.0
    env_file:
      - .env
    ports:
      - '27018:27017'
    volumes:
      - ./data:/data/db
      - ./docker-entrypoint-initdb.d/init.js:/docker-entrypoint-initdb.d/init.js:ro

The .env file looks like :

# MongoDB configuration
MONGO_INITDB_ROOT_USERNAME=admin
MONGO_INITDB_DATABASE=users
MONGO_INITDB_ROOT_PASSWORD=pass

# User specific
DB_USER=user_login
DB_PASSWORD=user_pass

Try this DSN :

mongodb://user_login:user_pass@mongo5-user-dev:27018/users
mongodb://admin:pass@mongo5-user-dev:27018/users
mongodb://user_login:user_pass@mongo5-user-dev:27017/users
mongodb://admin:pass@mongo5-user-dev:27017/users
...

Make a init.js that's look like :

db.getSiblingDB('users')
db.createCollection('users_collection')

db.createUser(
        {
            user: "user_login",
            pwd: "user_pass",
            roles: [
                {
                    role: "readWrite",
                    db: "users"
                }
            ]
        }
);

Docker logs says that user was successfully created...

I can connect to the container :

docker exec -it mongo5-user-dev mongo -u admin -p

But when the API runs, got an error... whatever is the DSN !

What i m missing please ?

Truely,

DaCoDeMaNiaK

Jean-Luc Aubert
  • 620
  • 5
  • 19

1 Answers1

0

Where is the NestJS API running? In the same docker network? or on the host machine? If it is on the host machine or outside the docker network, try accessing it with your host machine's ip (localhost if the API is running on the same machine as the mongodb container).

Hisham
  • 411
  • 3
  • 9
  • My API runs on the host... I tried to change to 127.0.0.1:27018 as my port map says... But always the same error... Although, i cannot connect to my container with my specific user, only admin user ! – Jean-Luc Aubert Aug 31 '23 at 12:40
  • As you mention @Hisham, i changed for "localhost:27018", but now, error raised is : "authentication failed"... lol – Jean-Luc Aubert Aug 31 '23 at 12:48
  • Is the container running as root / admin? A bit outdated, but might help: https://faun.pub/set-current-host-user-for-docker-container-4e521cef9ffc – Hisham Aug 31 '23 at 12:48
  • If you are getting auth failed error, probably you are getting connected, recheck the credentials that are set in the db or create a new mongodb user to test. – Hisham Aug 31 '23 at 12:51
  • Yes, i changed credentials for specific user, in fact, my prior password was composed of many special chars, and... specially a @ char and the DSN couldn't resolve the network address because of that... So, remove all and mount a new instance and it works... thx for help – Jean-Luc Aubert Aug 31 '23 at 13:16