How mongodb work in docker, How to connect with mongodb

you are saying mongodb is not on localhost. okay. After building image it is in container only. Then How to should I make the connection of my db. I am not sure to give the connection of my db to login the running application in docker

Hi @sdetweil I have just build an nodejs application image in docker it is running in docker machine ip 192.168.99.100:8088 . My need is I want to connect local system database using mongodb. in application env file is already there to make a connection for mongodb. It is not connecting.

MONGODB_URI=mongodb://localhost:27017/SampleDB
SESSION_SECRET=FirstNodejsApplication
App_PORT = 8088

If i give like this when i click the login button it is not authorizing the username and password from the sampledb (users collection). I am getting 192.168.99.100:login net:empty response only.

To solve this issue how to connect with mongodb .

I tried with the following connection . But unable to connect the db into that running application.

MONGODB_URI=mongodb://localhost:27017/SampleDB // localhost
MONGODB_URI=mongodb://192.168.99.100:27017/SampleDB //docker macine ip
MONGODB_URI=mongodb://127.0.0.1:27017/SampleDB //mongodb ip
MONGODB_URI=mongodb://192.168.1.88:27017/SampleDB //local machine ip

Can you share the steps which i needs to follow to connect the sampleDb of my system or any other system . which ip should I use?

Please help me

you need the database container ip address…

if u name the database container when u do docker run, then you can issue

docker inspect --format="{{.NetworkSettings.Networks.$2.IPAddress}}" $1   xxxxx 

where xxxxx is

the container name
the container id
the id is returned from docker run
or looked up via docker ps

AND you must tell mongo that it should accept connections from outside the container,
the easiest way is when starting mongo’s server daemon

mongod --bind_ip_all

(if u docker inspect the pre-built mongo image, you will see this as the parms on their entrypoint command)

You could create both containers on the same overlay network. Then the app container could talk with MongoDB. See docker connect a service to the overlay network.

Another thing you need to consider is MongoDB data persistence. When MongoDB container moves to another node, it should be able to read the existing data, or else, data will get lost. Also you will want a MongoDB ReplicaSet or Sharded cluster to better protect your data. You may refer to the discussions in the question: Data(base) persistence in docker swarm mode.

mongod.config file

> systemLog:
> destination: file
> path: c:\data\log\mongod.log
> storage:
> dbPath: c:\data\db
> net:
> bindIp: 127.0.0.1, 192.168.1.88, 192.168.1.174, 172.17.0.2, 0.0.0.0
> port: 27017

docker inspect continer_id

$ docker inspect 93285309274b
[
{
“Id”: “93285309274b5912937a6a2ac43ab047e24b9f45ce762061c5ad49467da07b3b”,
“Created”: “2018-01-24T06:16:37.845156623Z”,
“Path”: “docker-entrypoint.sh”,
“Args”: [
“mongod”
],
“State”: {
“Status”: “running”,
“Running”: true,
“Paused”: false,
“Restarting”: false,
“OOMKilled”: false,
“Dead”: false,
“Pid”: 3210,
“ExitCode”: 0,
“Error”: “”,
“StartedAt”: “2018-01-24T06:16:38.340897415Z”,
“FinishedAt”: “0001-01-01T00:00:00Z”
},
“Image”: “sha256:0f57644645eb53a3d2256f460ade116ad3590252c28f63e5136c026423dc8286”,
“ResolvConfPath”: “/mnt/sda1/var/lib/docker/containers/93285309274b5912937a6a2ac43ab047e24b9f45ce762061c5ad49467da07b3b/resolv.conf”,
“HostnamePath”: “/mnt/sda1/var/lib/docker/containers/93285309274b5912937a6a2ac43ab047e24b9f45ce762061c5ad49467da07b3b/hostname”,
“HostsPath”: “/mnt/sda1/var/lib/docker/containers/93285309274b5912937a6a2ac43ab047e24b9f45ce762061c5ad49467da07b3b/hosts”,
“LogPath”: “/mnt/sda1/var/lib/docker/containers/93285309274b5912937a6a2ac43ab047e24b9f45ce762061c5ad49467da07b3b/93285309274b5912937a6a2ac43ab047e24b9f45ce762061c5
ad49467da07b3b-json.log”,
“Name”: “/suspicious_sinoussi”,
“RestartCount”: 0,
“Driver”: “aufs”,
“MountLabel”: “”,
“ProcessLabel”: “”,
“AppArmorProfile”: “”,
“ExecIDs”: null,
“HostConfig”: {
“Binds”: null,
“ContainerIDFile”: “”,
“LogConfig”: {
“Type”: “json-file”,
“Config”: {}
},
“NetworkMode”: “default”,
“PortBindings”: {},
“RestartPolicy”: {
“Name”: “no”,
“MaximumRetryCount”: 0
},
“AutoRemove”: false,
“VolumeDriver”: “”,
“VolumesFrom”: null,
“CapAdd”: null,
“CapDrop”: null,
“Dns”: [],
“DnsOptions”: [],
“DnsSearch”: [],
“ExtraHosts”: null,
“GroupAdd”: null,
“IpcMode”: “”,
“Cgroup”: “”,
“Links”: null,
“OomScoreAdj”: 0,
“PidMode”: “”,
“Privileged”: false,
“PublishAllPorts”: false,
“ReadonlyRootfs”: false,
“SecurityOpt”: null,
“UTSMode”: “”,
“UsernsMode”: “”,
“ShmSize”: 67108864,
“Runtime”: “runc”,
“ConsoleSize”: [
33,
45
],
“Isolation”: “”,
“CpuShares”: 0,
“Memory”: 0,
“NanoCpus”: 0,
“CgroupParent”: “”,
“BlkioWeight”: 0,
“BlkioWeightDevice”: null,
“BlkioDeviceReadBps”: null,
“BlkioDeviceWriteBps”: null,
“BlkioDeviceReadIOps”: null,
“BlkioDeviceWriteIOps”: null,
“CpuPeriod”: 0,
“CpuQuota”: 0,
“CpuRealtimePeriod”: 0,
“CpuRealtimeRuntime”: 0,
“CpusetCpus”: “”,
“CpusetMems”: “”,
“Devices”: [],
“DeviceCgroupRules”: null,
“DiskQuota”: 0,
“KernelMemory”: 0,
“MemoryReservation”: 0,
“MemorySwap”: 0,
“MemorySwappiness”: -1,
“OomKillDisable”: false,
“PidsLimit”: 0,
“Ulimits”: null,
“CpuCount”: 0,
“CpuPercent”: 0,
“IOMaximumIOps”: 0,
“IOMaximumBandwidth”: 0
},
“GraphDriver”: {
“Data”: null,
“Name”: “aufs”
},
“Mounts”: [
{
“Type”: “volume”,
“Name”: “ddc35ea7fad8015080c30c58db7bf470aa87da4a3940a13e7a9b6677ba92095a”,
“Source”: “/mnt/sda1/var/lib/docker/volumes/ddc35ea7fad8015080c30c58db7bf470aa87da4a3940a13e7a9b6677ba92095a/_data”,
“Destination”: “/data/configdb”,
“Driver”: “local”,
“Mode”: “”,
“RW”: true,
“Propagation”: “”
},
{
“Type”: “volume”,
“Name”: “52857036dd769165971b17bd2fd0574020bd2ae766ee0b4dd478564f7c85005a”,
“Source”: “/mnt/sda1/var/lib/docker/volumes/52857036dd769165971b17bd2fd0574020bd2ae766ee0b4dd478564f7c85005a/_data”,
“Destination”: “/data/db”,
“Driver”: “local”,
“Mode”: “”,
“RW”: true,
“Propagation”: “”
}
],
“Config”: {
“Hostname”: “93285309274b”,
“Domainname”: “”,
“User”: “”,
“AttachStdin”: false,
“AttachStdout”: true,
“AttachStderr”: true,
“ExposedPorts”: {
“27017/tcp”: {}
},
“Tty”: false,
“OpenStdin”: false,
“StdinOnce”: false,
“Env”: [
“PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin”,
“GOSU_VERSION=1.10”,
“JSYAML_VERSION=3.10.0”,
“GPG_KEYS=2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5”,
“MONGO_PACKAGE=mongodb-org”,
“MONGO_REPO=repo.mongodb.org”,
“MONGO_MAJOR=3.6”,
“MONGO_VERSION=3.6.2”
],
“Cmd”: [
“mongod”
],
“ArgsEscaped”: true,
“Image”: “mongo”,
“Volumes”: {
"/data/configdb": {},
"/data/db": {}
},
“WorkingDir”: “”,
“Entrypoint”: [
docker-entrypoint.sh
],
“OnBuild”: null,
“Labels”: {}
},
“NetworkSettings”: {
“Bridge”: “”,
“SandboxID”: “79e59e21f4bd4c3ccdea93f6f1fe994b7efa52ea3921cd9ad6be7623e0909c82”,
“HairpinMode”: false,
“LinkLocalIPv6Address”: “”,
“LinkLocalIPv6PrefixLen”: 0,
“Ports”: {
“27017/tcp”: null
},
“SandboxKey”: “/var/run/docker/netns/79e59e21f4bd”,
“SecondaryIPAddresses”: null,
“SecondaryIPv6Addresses”: null,
“EndpointID”: “afd3e993b738b301a00db87f2bd06665263adf78b64daaaf0d2f0f5e549fe12a”,
“Gateway”: “172.17.0.1”,
“GlobalIPv6Address”: “”,
“GlobalIPv6PrefixLen”: 0,
“IPAddress”: “172.17.0.2”,
“IPPrefixLen”: 16,
“IPv6Gateway”: “”,
“MacAddress”: “02:42:ac:11:00:02”,
“Networks”: {
“bridge”: {
“IPAMConfig”: null,
“Links”: null,
“Aliases”: null,
“NetworkID”: “d68232955f6b25cbe38cea47b3858df1f3386c4c60eff8403d8567afb1806818”,
“EndpointID”: “afd3e993b738b301a00db87f2bd06665263adf78b64daaaf0d2f0f5e549fe12a”,
“Gateway”: “172.17.0.1”,
“IPAddress”: “172.17.0.2”,
“IPPrefixLen”: 16,
“IPv6Gateway”: “”,
“GlobalIPv6Address”: “”,
“GlobalIPv6PrefixLen”: 0,
“MacAddress”: “02:42:ac:11:00:02”,
“DriverOpts”: null
}
}
}
}
]

now what should I pass it in to my env.file to connect mongodb

MONGODB_URI=mongodb://172.17.0.1.2:27017/PMS_DB
SESSION_SECRET=sample
App_PORT = 8088

Is this right

@junius I am just running my application in docker for that application i want to access my local db

how to connect i dont know. in env file I have mentioned like

MONGODB_URI=mongodb://192.168.1.88:27017/PMS_DB
SESSION_SECRET=sample
App_PORT = 8088

here 19.168.1.88 is my system ip address

if i run this application in my system i will run by http://localhost:8088/login so that it will connect my system db and able to login. in docker I dont have an idea to connect my system db. and also application is not running in localhost:8088 instead it is running in docker machine ip that is 192.168.99.100:8088 only but database I used mongodb://192.168.1.88:27017/pms-db

how to connect this with my docker application

ok you are using words that are vague… what does ‘local’ mean?

do you mean

  1. the application (client) is running inside the docker container, and
    wants to access the mongo database server running on the docker host

  2. the mongo database server is running in a container and the application is
    running on the docker host

not sure about your requirements.
there are multiple ways you could connect to mongodb.
option1: run mongodb by exposing the port to host.
For example, run mongodb: $ docker run -d -p 27017:27017 --name m1 mongo on host1. Then could connect to it mongo --host host1.

option2: run on the overlay network.

  1. create network: docker network create --driver overlay my-network
  2. create mongodb: docker service create --replicas 1 --network my-network --name mymongo mongo
  3. create the application container on the same network, then inside the app container, could connect to mongodb by like mongo --host mymongo.
1 Like

@junius @sdetweil

My requirement:

  1. I want to connect a dynamic database (LAN connection - local system’s db) in to docker. in docker machine ip 192.168.99.100:8082 in this my sample application is running . For this application I want to connect dynamic databases (different machine mongodb database which is connected by LAN) . How do I connect the dynamic database with docker running application.

  2. How do I connect and run the local system database in to docker. How to run mongodb database.

what is use of docker compose.yml file? How and where should I use this? Explain the structure of the docker-compose.yml file

docker-compose is a separate application that attempts to make multi-container solutions easier to construct and run, using a single input file, a ‘compose’ file.

it has its own syntax, which you can read about by doing a google search for docker-compose.

it does NOT do everything, so the problems u are having remain

How do I achieve this?

see my other reply

I have see no answer to this question, which seems to be:

Having MongoDb working in a container, how do I connect to the database from outside the container?

The ip address returned by docker inspect doesn’t help.

Anyone can help?

you are saying mongodb is not on localhost. okay. After building image it is in container only. Then How to should I make the connection of my db. I am not sure to give the connection of my db to login the running application in docker

Thank you very much!

For docker version 18.03+ in Windows,
db.url=mongodb://host.docker.internal:27017/my_database
Also on C:\Windows\System32\drivers\etc\hosts, comment any lines showing docker that you did not add

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