For some reason I couldn't get it to work using other the stackoverflow posts on this topic.
I am getting:
MongoError: failed to connect to server [localhost:27017] on first connect.
I started my docker container and checked if mongo was working:
$ docker run --name my-mongo -d mongo
$ docker exec -it my-mongo bash
# mongo
MongoDB shell version v3.4.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.2
Server has startup warnings:
2017-03-19T01:23:53.047+0000 I STORAGE [initandlisten]
2017-03-19T01:23:53.047+0000 I STORAGE [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2017-03-19T01:23:53.047+0000 I STORAGE [initandlisten] ** See http://dochub.mongodb.org/core/prodnotes-filesystem
2017-03-19T01:23:53.290+0000 I CONTROL [initandlisten]
2017-03-19T01:23:53.290+0000 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2017-03-19T01:23:53.290+0000 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2017-03-19T01:23:53.290+0000 I CONTROL [initandlisten]
> db.col.insert({"a":1})
> db.col.find()
{ "_id" : ObjectId("58cde45479f772a8ea882ee1"), "a" : 1 }
I exited then started node in my OSX terminal and tried to connect:
$ node
> var mongoose = require("mongoose");
> mongoose.connect("mongodb://localhost:27017");
mongoose {...}
> MongoError: failed to connect to server [localhost:27017] on first connect ...
I tried many other url's:
mongoose.connect("mongodb://localhost:27017/test");
mongoose.connect("mongodb://localhost/test");
mongoose.connect("mongodb://127.0.0.1:27017");
So just trying to connect to a mongodb container running on docker for mac and trying to connect to it using nodejs. How can I achieve this?
Thanks Nehal for the comment.
The answer lies here https://docs.docker.com/docker-for-mac/networking/#known-limitations-use-cases-and-workarounds
Basically, you cannot see a docker0 interface in macOS which means your unable to route traffic to containers. However, that can be solved using port forwarding.
All I have to change is the docker run command:
docker run -d -p 27017:27017 --name my-mongo mongo
This means that you expose the Linux port, which is docker in this instance, and forward it to your Mac (-p). The -d flag runs the process in the background.
Then mongoose.connect("mongodb://localhost:27017/test"); should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With