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

<p>I'm connecting to the context on cmd line using:</p>

<pre><code>kubectl config use-context CONTEXTNAME
</code></pre>

<p>With Python, I'm using:</p>

<pre><code>from kubernetes import client, config
config.load_kube_config(
    context = 'CONTEXTNAME'
)
</code></pre>

<p>To connect to MongoDB in cmd line:</p>

<pre><code>kubectl port-forward svc/mongo-mongodb 27083:27017 -n production &amp;
</code></pre>

<p>I then open a new terminal and use PORT_FORWARD_PID=$! to connect</p>

<p>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?</p>

FrancesSun
<p>Define a kubernetes service for example <a href="https://github.com/kubernetes/examples/blob/master/staging/nodesjs-mongodb/mongo-service.yaml" rel="nofollow noreferrer">like this</a>, and then reference your mongodb using a connection string similar to <code>mongodb://&lt;service-name&gt;.default.svc.cluster.local</code></p>
