skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search