'MongooseModule: Unable to connect to the database. On a dockerized Nestjs app with Mongo
I'm trying to start a react-nestjs-mongo db application with docker-compose but for some reason it doesnt seems to work. docker-compose --build output shows something like this:
server | [Nest] 32 - 06/06/2021, 3:10:25 AM [MongooseModule] Unable to connect to the database. Retrying (7)... +33006ms
database | {"t":{"$date":"2021-06-06T03:10:27.406+00:00"},"s":"I", "c":"STORAGE", "id":22430,
"ctx":"WTCheckpointThread","msg":"WiredTiger message","attr":{"message":"[1622949027:406819][1:0x7f9ae2c3b700], WT_SESSION.checkpoint: [WT_VERB_CHECKPOINT_PROGRESS] saving checkpoint snapshot min: 7, snapshot max: 7 snapshot count: 0, oldest timestamp: (0, 0) , meta checkpoint timestamp: (0, 0)"}}
Here's my docker-compose:
version: "3.5"
services: client:
container_name: client
build: ./client
ports:
- 3000:3000
depends_on:
- server
server:
container_name: server
build: ./server
ports:
- 8000:8000
depends_on:
- mongodb
links:
- mongodb
mongodb:
container_name: database
image: mongo
restart: always
ports:
- "27017:27017"
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example
And my app.modules.ts file looks like this:
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MongooseModule } from '@nestjs/mongoose';
@Module({
imports: [
MongooseModule.forRoot('mongodb://localhost:27017/nestjs', {
useNewUrlParser: true,
}),
],
controllers: [AppController],
providers: [AppService],
})
class AppModule {}
Can someone explain me why this isn't working?
Solution 1:[1]
You are using docker-compose . Thus you are not connecting 'localhost' but it should be address of your 'service' you defined in docker-compose file.
instead of 'mongodb://localhost:27017/nestjs' , you should use (in your case service name you defined in docker-compose is mongodb . You should use 'mongodb://mongodb:27017/nestjs'
Solution 2:[2]
I just faced the same issue!
In order to solve it you need to:
- use container name instead of localhost (as manish also suggests)
- provide username and password before host and port as explained in mongose doc: https://mongoosejs.com/docs/connections.html
- inialize the database as explained in this question: Use MongoDB with docker-compose: create database and user
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Manish P |
| Solution 2 | Lorenzo Piersante |
