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
2
Answers
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 usemongodb://user:password@mongo_db:27017
to specify themongo_db
service as what you’re trying to connect toIt’s help for me (based on Jays answer):
connection string (password and username not needed in this case)
mongo_db
Full code
docker-compose.development.yml: