Connecting to MongoDB in Kubernetes pod with kubernetes-client using Python

10/9/2019

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?

-- Fran
kubectl
kubernetes
kubernetes-python-client
mongodb
python-3.x

2 Answers

10/9/2019

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!

-- Valentin
Source: StackOverflow

10/10/2019

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

-- Belly Buster
Source: StackOverflow