简体   繁体   中英

Unable to Connect MongoDB with NestJS ( Docker )

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM