node.js 从主机连接到 mongo docker 容器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33336773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Connecting to mongo docker container from host
提问by ggeise
I'm running Docker on OS X with:
我在 OS X 上运行 Docker:
docker run --name mongo -p 27017:27017 -v ./data/db:/data/db -d mongo mongod
and using the ip I get from:
并使用我从以下地址获得的 IP:
docker inspect --format '{{ .NetworkSettings.IPAddress }}' <cid>
in:
在:
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var url = 'mongodb://<ip>:27017';
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
db.close();
});
and I'm getting a timed out error.
我收到超时错误。
I'm using the official mongo repository from Docker Hub. Is there any additional setup that I need to do in order to connect from the host?
我正在使用来自 Docker Hub 的官方 mongo 存储库。为了从主机连接,我需要做任何额外的设置吗?
回答by Adrian Mouat
Is the node.js code being run from a container or from the host?
node.js 代码是从容器还是从主机运行?
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.
这将起作用,因为您使用-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:
如果代码在容器内运行,最好重写它以使用链接并按名称引用 mongo 容器,例如:
var url = 'mongodb://mongo:27017';
Then when you launch the container with the Node.js code, you can just do something like:
然后,当您使用 Node.js 代码启动容器时,您可以执行以下操作:
docker run -d --link mongo:mongo my_container
Docker will then add an entry to /etc/hostsinside the container so that the name mongoresolves to the IP of the mongo container.
Docker 然后将/etc/hosts在容器内部添加一个条目,以便名称mongo解析为 mongo 容器的 IP。
回答by fullstacklife
If you use a user defined network you should be able to pick it up without linking or specifying 27017
如果您使用用户定义的网络,您应该能够在不链接或指定 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;
});
回答by roll
Another option for anyone who use docker-compose
使用 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
你可以使用 url 字符串连接
MongoClient.connect("mongodb://root:example@localhost:27017")
.then(()=>{
console.log("db connect success");
})
.catch((err)=>{
throw err
});

