我有以下簡化設計:一個mongodb容器和一個「python-client」泊塢窗容器,鏈接到前者。這是我簡單的docker-compose.yml
文件:無法連接到來自另一個容器的mongodb泊塢窗容器
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:[email protected]:27017/admin"
- "MONGODB_DB=historictraffic"
我能夠建立使用pymongo
從使用mongodb://admin:[email protected]:27017/admin
連接字符串我的主機連接成功(注意localhost
):
$ ipython
from pymongo import MongoClient
mongo = MongoClient('mongodb://admin:[email protected]: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:[email protected]: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
有誰知道如何解決呢?謝謝。
我有同樣的確切問題... – thearrow3456