Unable to Connect MongoDB with NestJS ( Docker )

Unable to Connect MongoDB with NestJS ( Docker )

Questions : Unable to Connect MongoDB with NestJS ( Docker )


I have my app and mongo db into a docker in4codes_nestjs file, however when I run docker-compose up, in4codes_nestjs I got the error ERROR [MongooseModule] in4codes_nestjs Unable to connect to the database. I’been in4codes_nestjs troubleshooting the yml file with no in4codes_nestjs success. Any help is very appreciated.


version: '3.6' services: main: container_name: main build: context: . target: development volumes: - .:/usr/src/app ports: - ${SERVER_PORT}:${SERVER_PORT} - 9229:9229 command: npm run start:debug env_file: - .env networks: - webnet depends_on: - mongo_db mongo_db: container_name: mongo_db hostname: '${MONGO_HOST}' image: mongo:4.4.11-rc0-focal networks: - webnet environment: MONGO_INITDB_ROOT_USERNAME: '${MONGO_USERNAME}' MONGO_INITDB_ROOT_PASSWORD: '${MONGO_PASSWORD}' MONGO_INITDB_DATABASE: '${MONGO_DATABASE_NAME}' expose: - '27017' networks: webnet: driver: bridge 

and the mongo URI : in4codes_nestjs MONGO_URI=mongodb://user:[email protected]:27017

Total Answers 2

Answers 1 : of Unable to Connect MongoDB with NestJS ( Docker )

As you’re running the services through in4codes_node.js docker-compose, the internal in4codes_node.js docker-compose network should be used. in4codes_node.js Each service’s name is a host in the in4codes_node.js compose network, so instead of using in4codes_node.js localhost, which is the localhost of the in4codes_node.js container itself, you should use in4codes_node.js mongodb://user:[email protected]_db:27017 in4codes_node.js to specify the mongo_db service as what in4codes_node.js you’re trying to connect to



Answers 2 : of Unable to Connect MongoDB with NestJS ( Docker )

It’s help for me (based on Jays answer):

connection string (password and username in4codes_node.js not needed in this case) mongo_db


Full code

@Module({ imports: [ MongooseModule.forRoot(url), MongooseModule.forFeature([{ name: CatImage.name, schema: CatSchema }]), ], controllers: [AppController], providers: [AppService], }) 


mongodb: image: mongo environment: - MONGODB_DATABASE="test" ports: - 27017:27017 volumes: - mongodb_container:/data/db