简体   繁体   English

无法使用MongoJavaDriver连接到mongodb容器

[英]Unable to connect to mongodb container using MongoJavaDriver

I can across this problem and found multiple people online with the same issue. 我可以解决此问题,并在网上找到同一问题的多个人。

I had been trying: 我一直在尝试:

new MongoClient(new ServerAddress("0.0.0.0", 27017), mongoClientBuilder.build());

I also tried "localhost" and "127.0.0.1" with no luck. 我也尝试过"localhost""127.0.0.1" ,但是没有运气。 The issues raised online had the same stack trace: 在线提出的问题具有相同的堆栈跟踪:

    INFO: Exception in monitor thread while connecting to server localhost:27017
com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.connection.SocketStream.open(SocketStream.java:63)
    at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:114)
    at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:128)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)
    at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
    ... 3 more

You need to expose the port to the docker container when you create it: 创建端口时,需要将端口公开给Docker容器:

docker pull mongo
docker run --name mongo -d -p 27017:27017 mongo

and then you can connect to localhost port 27017 然后您可以连接到本地主机端口27017

First you need the container id: 首先,您需要容器ID:

docker ps

You need to get the specific ip for the container: 您需要获取容器的特定IP:

$ docker exec -it ${container_id} bash

This will open a terminal session within your container. 这将在您的容器中打开一个终端会话。 Next run (in the container terminal): 下次运行(在集装箱码头):

$ cat /etc/hosts

This will print out the hosts, including an entry where the name is the first few characters of the container id. 这将打印出主机,包括一个名称为容器ID的前几个字符的条目。

The output will look something like this: 输出将如下所示:

127.0.0.1   localhost
...
...
172.17.0.2  container_id

The IP next to your container id is what you want to use: 容器ID旁边的IP是您要使用的IP地址:

new MongoClient(new ServerAddress("172.17.0.2", 27017), mongoClientBuilder.build());

If anyone has a more elegant solution I would be interested to hear it. 如果有人有更好的解决方案,我将很高兴听到。 For example this ip may change, though in my experience it doesn't when the container restarts. 例如,此ip可能会更改,但是以我的经验,容器重启时不会更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM