Connecting to mongo docker container from host Connecting to mongo docker container from host docker docker

Connecting to mongo docker container from host


Is the node.js code being run from a container or from the host?

If it's on the host, just use the localhost address i.e:

var url = 'mongodb://localhost:27017';

This will work because you published the port with -p 27017:27017.

If the code is running inside a container, it would be best to rewrite it to use links and referring to the mongo container by name e.g:

var url = 'mongodb://mongo:27017';

Then when you launch the container with the Node.js code, you can just do something like:

docker run -d --link mongo:mongo my_container

Docker will then add an entry to /etc/hosts inside the container so that the name mongo resolves to the IP of the mongo container.


If you use a user defined network you should be able to pick it up without linking or specifying 27017

const MONGO_NAME_STR = "mongodb://" + "your_docker_container_name";var db = {};mongo_client.connect(MONGO_NAME_STR, function(err, _db){  //some err handling  db = _db;});


Another option for anyone who use docker-compose

version: '3.1'services:  mongo:    image: mongo    container_name: "mongo"    restart: always    environment:      MONGO_INITDB_ROOT_USERNAME: root      MONGO_INITDB_ROOT_PASSWORD: example    volumes:      - './dockervolume/mongodb:/data/db'    ports:      - 27017:27017

And u can connect using the url string

    MongoClient.connect("mongodb://root:example@localhost:27017")        .then(()=>{            console.log("db connect success");        })        .catch((err)=>{            throw err        });