Reputation: 45
I have my app and mongo db into a docker file, however when I run docker-compose up, I got the error ERROR [MongooseModule] Unable to connect to the database. I'been troubleshooting the yml file with no success. Any help is very appreciated.
docker-compose.yml
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 : MONGO_URI=mongodb://user:password@localhost:27017
Upvotes: 2
Views: 3414
Reputation: 840
It's help for me (based on Jays answer):
connection string (password and username not needed in this case) mongo_db
mongodb://mongo_db:27017
Full code
@Module({
imports: [
MongooseModule.forRoot(url),
MongooseModule.forFeature([{ name: CatImage.name, schema: CatSchema }]),
],
controllers: [AppController],
providers: [AppService],
})
docker-compose.development.yml:
mongodb:
image: mongo
environment:
- MONGODB_DATABASE="test"
ports:
- 27017:27017
volumes:
- mongodb_container:/data/db
Upvotes: 0
Reputation: 70201
As you're running the services through docker-compose, the internal docker-compose network should be used. Each service's name is a host in the compose network, so instead of using localhost
, which is the localhost of the container itself, you should use mongodb://user:password@mongo_db:27017
to specify the mongo_db
service as what you're trying to connect to
Upvotes: 3