How mongodb work in docker, How to connect with mongodb

HI,

For connecting to remote mongo (which started into container):
1. Pull mongo image from docker hub: docker pull mongo
2. Run image: docker run --name my_mongo -p 27017:27017 -d mongo
3. I connected to mongo from my nodejs app:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Create a new MongoClient
const client = new MongoClient(url, { useUnifiedTopology: true });

// Use connect method to connect to the Server
client.connect(function(err) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  client.close();
});

Hope it will help anyone :slight_smile:

Best regards,
Daniil G

if mongodb is installed on dockerhost, you need to change mongod.conf settings, under net
change bindIp from 127.0.0.1 to 0.0.0.0 # this will accept remote connections
and change MONGODB_URI=mongodb://<YOURMACHINEIP>:27017/SampleDB

I hope this helps

Hi,
I tried this and got:

C:\Users\RachelCohen\DockerProject\ApiGenerator\node_modules\mongodb\lib\utils.js:502
                    throw error;
                    ^

AssertionError [ERR_ASSERTION]: null == MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
    at Timeout._onTimeout (C:\Users\RachelCohen\DockerProject\ApiGenerator\node_modules\mongodb\lib\sdam\topology.js:330:38)
    at listOnTimeout (node:internal/timers:557:17)    at processTimers (node:internal/timers:500:7) {
  reason: TopologyDescription {    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined,
    servers: Map(1) {

Are you know what the problem is?
thank you

Thanks man. This did the trick for me!

This topic was automatically closed after 10 days. New replies are no longer allowed.