简体   繁体   中英

Connect NodeJS App Running Locally to MongoDB on docker container

I am getting error when attempting connection from localhost to MongoDB running in docker container

Error: Could not call function connect due to MongoServerSelectionError: //getaddrinfo ENOTFOUND mongo at MongoServerSelectionError: getaddrinfo ENOTFOUND mongo\n //at Timeout._onTimeout

Use Case -

I start my NodeApp locally via the npm start command The App attempts a connection to MongoDB

I have already started my MongoDB as a container via command docker-compose -f docker-compose.backing-services.yaml up -d --build mongo mongo02 mongo03

Below is the ' docker-compose.backing-services.yaml ' file

services:
  mongo:
    image: mongo:4.4.3
    restart: always
    container_name: mongodb
    entrypoint: ['/usr/bin/mongod', '--noauth', '--bind_ip_all', '--replSet', 'rs0']
    env_file:
      - ./.env
    ports:
      - 27017:27017
    volumes:
      - mongodata01:/data/db
    networks:
      - my-network
  mongo02:
    image: mongo:4.4.3
    restart: always
    container_name: mongodb02
    entrypoint: ['/usr/bin/mongod', '--noauth', '--bind_ip_all', '--replSet', 'rs0']
    env_file:
      - ./.env
    ports:
      - 27018:27017
    volumes:
      - mongodata02:/data/db
    networks:
      - my-network
  mongo03:
    image: mongo:4.4.3
    restart: always
    container_name: mongodb03
    entrypoint: ['/usr/bin/mongod', '--noauth', '--bind_ip_all', '--replSet', 'rs0']
    env_file:
      - ./.env
    ports:
      - 27019:27017
    volumes:
      - mongodata03:/data/db
    networks:
      - my-network

volumes:
  mongodata01:
  mongodata02:
  mongodata03:
networks:
  my-network:
    name: my-network

Now in my app when I try to connect/ping mongodb

uri = 'mongodb://mongo,mongo02,mongo03:27017'
//Tried different URs too e.g. mongodb://mongo,mongo02,mongo03:27017/?replicaset=rs0 , mongodb://mongo:27017
connectionOptions = { useUnifiedTopology: true }

new MongoClient(uri, connectionOptions).ping

//Throws error - Error: Could not call function connect due to MongoServerSelectionError: //getaddrinfo ENOTFOUND mongo at MongoServerSelectionError: getaddrinfo ENOTFOUND mongo\n    //at Timeout._onTimeout

Can someone tell what is wrong or what else is missing?

For mongo URI you must use your mongodb service name instead 127.0.0.1 or localhost. You are missing the environment variable in your docker-compose.backing-services.yaml file, like this:

 environment:
      - MONGO_URI=mongodb://mongodb-myapp:27017/myapp

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