Home > database >  MongoServerSelectionError: Server selection timed out after 30000 while connecting from node:alpine
MongoServerSelectionError: Server selection timed out after 30000 while connecting from node:alpine

Time:01-28

I have following docker-compose.yaml

version: '3.8'

networks:
  mongodb:
    name: mongodb
    driver: bridge
  host:
    name: host
    driver: host

services:
  nodejs-server:  
    networks:
      - mongodb
      - host
    build:
      context: ./api
      network: host
    ports:
      - "8000:8000"
    container_name: node-api
    volumes:
       - ./api:/usr/src/app/api
       - /usr/src/app/api/node_modules

mongodb:
    image: mongo
    networks:
      mongodb:
    container_name: mongodb
    ports:
      - 27017:27017
    restart: always
    environment:
      MONGO_INITDB_DATABASE: Demo
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: password

and index.js file in Express server

const { MongoClient } = require('mongodb');
const mongoDB = 'mongodb://admin:password@mongodb:27017';
const mongoClient = new MongoClient(mongoDB);
app.get('/mongo', async (req, res) => {

    console.log('connecting...');
    await mongoClient.connect();
    console.log('connected...');
    const database = mongoClient.db('insertDB');
    const haiku = database.collection('haiku');
});

When I run the app, it stucks on await mongoClient.connect(); and throws following exception:

MongoServerSelectionError: Server selection timed out after 30000 ms

So when log in to docker container in nodejs-server if I run ping:

/usr/src/app/api # ping mongodb
PING mongodb (172.21.0.2): 56 data bytes
64 bytes from 172.21.0.2: seq=0 ttl=64 time=0.146 ms
64 bytes from 172.21.0.2: seq=1 ttl=64 time=0.122 ms
64 bytes from 172.21.0.2: seq=2 ttl=64 time=0.199 ms

So I am not sure why driver cannot connect? Would it be port problem or something else?

CodePudding user response:

You can't have your node-api container inside the "host" network and another network. I am not exactly sure what your docker-compose file will produce, but I assume it puts the node-api into the host network. The host network in docker is a special network as it disables network encapsulation. This means there is no network namespace created for the container and it can't connect to other docker networks.

What you need to do is either put node-api inside only the mongodb network or change your monogdb connection string to mongodb://admin:password@localhost:27017 as port 27017 on your host should be mapped to the correct port inside the mongodb container.

  • Related