我有以下简化设计:一个mongodb容器和一个链接到前者的“python-client”docker容器。这是我简化的docker-compose.yml
文件:
mongodb:
build: "mongodb"
dockerfile: "Dockerfile"
hostname: "mongodb.local"
ports:
- "27017:27017"
client:
build: "client"
dockerfile: "Dockerfile"
hostname: "client.local"
links:
- "mongodb:mongodb"
environment:
- "MONGODB_URL=mongodb://admin:admin@mongodb:27017/admin"
- "MONGODB_DB=historictraffic"
我可以使用pymongo
连接字符串从我的主机使用mongodb://admin:admin@localhost:27017/admin
建立成功的连接(注意localhost
):
$ ipython
from pymongo import MongoClient
mongo = MongoClient('mongodb://admin:admin@localhost:27017/admin')
db = mongo.test
col = db.test
col.insert_one({'x': 1})
# This works
但我无法从客户端容器连接。显然链接是正确的:
/ # cat /etc/hosts
172.17.0.27 client.local client
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.26 historictraffic_mongodb_1 mongodb
172.17.0.26 mongodb mongodb historictraffic_mongodb_1
172.17.0.26 mongodb_1 mongodb historictraffic_mongodb_1
但是当我做同样的测试时,它失败了:
/ # ipython
from pymongo import MongoClient
mongo = MongoClient('mongodb://admin:admin@mongodb:27017/admin')
db = mongo.test
col = db.test
col.insert_one({'x': 2})
---------------------------------------------------------------------------
ServerSelectionTimeoutError Traceback (most recent call last)
<ipython-input-5-c5d62e5590d5> in <module>()
----> 1 col.insert_one({'x': 2})
/usr/lib/python2.7/site-packages/pymongo/collection.pyc in insert_one(self, document)
464 if "_id" not in document:
465 document["_id"] = ObjectId()
--> 466 with self._socket_for_writes() as sock_info:
467 return InsertOneResult(self._insert(sock_info, document),
468 self.write_concern.acknowledged)
/usr/lib/python2.7/contextlib.pyc in __enter__(self)
15 def __enter__(self):
16 try:
---> 17 return self.gen.next()
18 except StopIteration:
19 raise RuntimeError("generator didn't yield")
/usr/lib/python2.7/site-packages/pymongo/mongo_client.pyc in _get_socket(self, selector)
661 @contextlib.contextmanager
662 def _get_socket(self, selector):
--> 663 server = self._get_topology().select_server(selector)
664 try:
665 with server.get_socket(self.__all_credentials) as sock_info:
/usr/lib/python2.7/site-packages/pymongo/topology.pyc in select_server(self, selector, server_selection_timeout, address)
119 return random.choice(self.select_servers(selector,
120 server_selection_timeout,
--> 121 address))
122
123 def select_server_by_address(self, address,
/usr/lib/python2.7/site-packages/pymongo/topology.pyc in select_servers(self, selector, server_selection_timeout, address)
95 if server_timeout == 0 or now > end_time:
96 raise ServerSelectionTimeoutError(
---> 97 self._error_message(selector))
98
99 self._ensure_opened()
ServerSelectionTimeoutError: mongodb:27017: [Errno 113] Host is unreachable
有谁知道如何解决它?谢谢。
答案 0 :(得分:0)
这次失败可能是因为mongo还没有开始。您可以在重试之间的短暂延迟重试连接,并且它应该在一次或两次尝试后起作用。