我已将mongodb作为StatefulSets部署在K8S上。当我尝试使用连接字符串URI(例如:mongodb://mongo-0.mongo:27017,mongo-1.mongo:27017 / cool_db)连接数据库时,它没有连接,但它正在连接并获取结果当我使用端点IP地址时。
# kubectl get sts
NAME READY AGE
mongo 2/2 7h33m
#kubectl get pods
NAME READY STATUS RESTARTS AGE
mongo-0 2/2 Running 0 7h48m
mongo-1 2/2 Running 2 7h47m
# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 10h
mongo ClusterIP None <none> 27017/TCP 7h48m
我正在尝试使用以下过程在python中使用连接字符串URI测试连接,但失败。
>>> import pymongo
>>> client = pymongo.MongoClient("mongodb://mongo-0.mongo:27017,mongo-1.mongo:27017/cool_db")
>>> db = client.cool_db
>>> print db.cool_collection.count()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/site-packages/pymongo/collection.py", line 1800, in count
return self._count(cmd, collation, session)
File "/usr/lib64/python2.7/site-packages/pymongo/collection.py", line 1600, in _count
_cmd, self._read_preference_for(session), session)
File "/usr/lib64/python2.7/site-packages/pymongo/mongo_client.py", line 1454, in _retryable_read
read_pref, session, address=address)
File "/usr/lib64/python2.7/site-packages/pymongo/mongo_client.py", line 1253, in _select_server
server = topology.select_server(server_selector)
File "/usr/lib64/python2.7/site-packages/pymongo/topology.py", line 235, in select_server
address))
File "/usr/lib64/python2.7/site-packages/pymongo/topology.py", line 193, in select_servers
selector, server_timeout, address)
File "/usr/lib64/python2.7/site-packages/pymongo/topology.py", line 209, in _select_servers_loop
self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: mongo-0.mongo:27017: [Errno -2] Name or service not known,mongo-1.mongo:27017: [Errno -2] Name or service not known
如果我们使用端点IP地址,那么我们将从DB获得响应。
>>> import pymongo
>>> client = pymongo.MongoClient("mongodb://10.244.1.8,10.244.2.9:27017/cool_db")
>>> db = client.cool_db
>>> print db.cool_collection.count()
0
>>>
我尝试使用其他URI,例如(client = pymongo.MongoClient(“ mongodb://mongo-0.mongo:27017 / cool_db”)),但无法正常工作。谁能帮我吗?
答案 0 :(得分:1)
在集群中,您应该使用<service-name>.<namespace-name>.svc.cluster.local
引用MongoDB Pod。
答案 1 :(得分:0)
我认为使用mongodb://mongo-0:27017
应该可以
答案 2 :(得分:0)
刚刚调试此问题。确保您的迷你库正在使用coredns。我的不是,一旦我进行了minikube删除和minikube启动,一切正常。
您需要查看此
$ kubectl get deploy -n kube-system
NAME READY UP-TO-DATE AVAILABLE AGE
coredns 1/1 1 1 31s
或这个
$ kubectl get po -n kube-system
NAME READY STATUS RESTARTS AGE
coredns-66bff467f8-9h6qb 1/1 Running 0 46s
etcd-minikube 1/1 Running 0 46s
kube-apiserver-minikube 1/1 Running 0 46s
kube-controller-manager-minikube 1/1 Running 0 45s
kube-proxy-d99lp 1/1 Running 0 46s
kube-scheduler-minikube 1/1 Running 0 46s
storage-provisioner 1/1 Running 0 49s