1

I have a MongoDB instance running on Kubernetes and I'm trying to connect to it using Python with the Kubernetes library.

I'm connecting to the context on cmd line using:

kubectl config use-context CONTEXTNAME

With Python, I'm using:

from kubernetes import client, config
config.load_kube_config(
    context = 'CONTEXTNAME'
)

To connect to MongoDB in cmd line:

kubectl port-forward svc/mongo-mongodb 27083:27017 -n production &

I then open a new terminal and use PORT_FORWARD_PID=$! to connect

I'm trying to get connect to the MongoDB instance using Python with the Kubernetes-client library, any ideas as to how to accomplish the above?

3
  • use a mongodb client library Commented Oct 9, 2019 at 21:01
  • To clarify, you can easily connect to DB from terminal but you have issue using Python? Commented Oct 10, 2019 at 15:07
  • @PjoterS That's correct, I am able to connect without issue in terminal, but facing issues when using kubernetes-client in python to connect. Commented Oct 10, 2019 at 19:06

2 Answers 2

1

Define a kubernetes service for example like this, and then reference your mongodb using a connection string similar to mongodb://<service-name>.default.svc.cluster.local

Sign up to request clarification or add additional context in comments.

Comments

0

My understanding is that you need to find out your DB Client Endpoint.

That could be achieved if you follow this article MongoDB on K8s make sure you got the URI for MongoDB. (example)

“mongodb://mongo-0.mongo,mongo-1.mongo,mongo-2.mongo:27017/dbname\_?”

and after that, you can call your DB client in Python script.

import pymongo
import sys

##Create a MongoDB client
client = pymongo.MongoClient('mongodb://......') 

##Specify the database to be used
db = client.test

##Specify the collection to be used
col = db.myTestCollection

##Insert a single document
col.insert_one({'hello':'world'})

##Find the document that was previously written
x = col.find_one({'hello':'world'})

##Print the result to the screen
print(x)

##Close the connection
client.close()

Hope that will give you an idea. Good luck!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.