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.
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 });