出于某种原因,我无法使用此主题上的其他stackoverflow帖子来使用它。
我正进入(状态:
MongoError: failed to connect to server [localhost:27017] on first connect
。
我启动了我的docker容器并检查mongo是否正常工作:
$ 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 }
我退出然后在我的OSX终端中启动了节点并尝试连接:
$ node
> var mongoose = require("mongoose");
> mongoose.connect("mongodb://localhost:27017");
mongoose {...}
> MongoError: failed to connect to server [localhost:27017] on first connect ...
我尝试了很多其他网址:
mongoose.connect("mongodb://localhost:27017/test");
mongoose.connect("mongodb://localhost/test");
mongoose.connect("mongodb://127.0.0.1:27017");
所以只是尝试连接到在docker上运行的mongodb容器,并尝试使用nodejs连接到它。我怎样才能做到这一点?
答案 0 :(得分:2)
感谢Nehal的评论。
答案就在这里https://docs.docker.com/docker-for-mac/networking/#known-limitations-use-cases-and-workarounds
基本上,您无法在macOS中看到docker0接口,这意味着您无法将流量路由到容器。但是,这可以通过端口转发来解决。
我需要更改的是docker run命令:
0
这意味着您公开Linux端口(此实例中为docker),并将其转发到Mac(docker run -d -p 27017:27017 --name my-mongo mongo
)。 -p
标志在后台运行该进程。
然后-d
应该有用。