title: Exceptions connecting to MongoDB Replica Set hosted inside Kubernetes with bitnami Helm chart
body: <p>We experienced some problems (timeout and notPrimary Exceptions) if we tried connecting to a MongoDB Replica Set hosted inside a kubernetes environment. We used bitnami helm chart 8.2.1.
  If we connect to an on-premise Replica Set installation of MongoDB 4.2.3, everything is ok. So we assume the problem must be with the configuration of the kubernetes installation. If I try to connect with MongoDB Compass to the kubernetes hosted instance, it worked but there are no other nodes visible in the HOSTS area. Connecting to the on-prem installation, there are all nodes visible.</p>
  <p>Using the on-prem installation is not an option, because we want that every of our developers has its own database (and of course the same configuration!).</p>
  <p>We installed the Replica set with the following script:</p>
  <pre><code>helm repo add bitnami https://charts.bitnami.com/bitnami
  
  # changing architecture or replica count, you must delete the persistance volume claims, otherwise mongodb starts with the previous configuration.
  $values = @&quot;
  architecture: replicaset
  replicaCount: 2
  replicaSetName: testRS
  
  auth:
    enabled: true
    rootPassword: admin
  
  &quot;@;
  
  &lt;# if I add these part to the above values variable, no connection could be established. Neither from MongoDB Compass nor from C# client
  externalAccess:
    enabled: true
    service:
      type: LoadBalancer
      port: 27017
    autoDiscovery:
      enabled: true
  
  serviceAccount:
    create: true
  
  rbac:
    create: true
  #&gt;
  
  
  
  if ( (helm list --namespace=&quot;infrastructure&quot; --filter=&quot;mongodb&quot; -q) -eq &quot;mongodb&quot;) {
    $values | helm upgrade mongodb bitnami/mongodb --values - --namespace infrastructure --recreate-pods --version 8.2.1
  }
  else {
    $values | helm install mongodb bitnami/mongodb --values - --namespace infrastructure --version 8.2.1
  }
  
  
  
  helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx
  $values = @&quot;
  tcp:
    # MongoDb
    27017: &quot;infrastructure/mongodb-headless:27017&quot;
  
  &quot;@;
  
  
  if ( (helm list --namespace=&quot;default&quot; --filter=&quot;ingress-nginx&quot; -q) -eq &quot;ingress-nginx&quot;) {
    $values | helm upgrade ingress-nginx ingress-nginx/ingress-nginx --values - --namespace default
  }
  else {
    $values | helm install ingress-nginx ingress-nginx/ingress-nginx --values - --namespace default
  }
  </code></pre>
  <p>The dotnet core sample application:</p>
  <pre><code>using System;
  using System.Threading.Tasks;
  using MongoDB.Driver;
  
  namespace MongoDBReplicaSet {
      class Program {
          static async Task Main(string[] args) {
              // Connecting to an on-premise installation (1 primary, 2 secondary) worked without any problems.
              //var connectionString = &quot;mongodb://root:admin@on-prem:27080/?authSource=admin&amp;replicaSet=testRS&amp;readPreference=primary&quot;;
  
              var connectionString =
                  &quot;mongodb://root:admin@localhost:27017/?authSource=admin&amp;readPreference=primary&quot;;
  
              await SimpleTask(connectionString);
              await Transaction(connectionString);
              Console.WriteLine(&quot;done.&quot;);
          }
  
  
          static async Task SimpleTask(string connectionString) {
              var client = new MongoClient(connectionString);
  
              var database = client.GetDatabase(&quot;TestDB&quot;);
              var collection = database.GetCollection&lt;TestData&gt;(nameof(TestData));
              /*
               * Can not connect to the kubernetes hosted replica set. MongoDB Compass and CLI can connect with the same connection string,
               * but in Compass, you don't see the other nodes under the HOSTS label
               *
               * System.TimeoutException: 'A timeout occured after 30000ms selecting a server using CompositeServerSelector{
               * Selectors = WritableServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }.
               * Client view of cluster state is { ClusterId : &quot;1&quot;, ConnectionMode : &quot;Automatic&quot;, Type : &quot;ReplicaSet&quot;,
               * State : &quot;Connected&quot;, Servers : [{ ServerId: &quot;{ ClusterId : 1, EndPoint : &quot;Unspecified/localhost:27017&quot; }&quot;,
               * EndPoint: &quot;Unspecified/localhost:27017&quot;, ReasonChanged: &quot;Heartbeat&quot;, State: &quot;Connected&quot;, ServerVersion: 4.2.8,
               * TopologyVersion: , Type: &quot;ReplicaSetSecondary&quot;, WireVersionRange: &quot;[0, 8]&quot; ...
               *
               *
               * if eliminating the replicaset parameter from the connection string, the exception is different:
               * MongoDB.Driver.MongoNotPrimaryException: 'Server returned not master error.', but sometimes it worked.
               * It seems the client connecting by random to the primary and the other time to the secondary?
               */
              await collection.InsertOneAsync(new TestData(Guid.NewGuid().ToString(), &quot;Test1&quot;, new DateTimeOffset(DateTime.Now)));
              Console.WriteLine(&quot;done simple task.&quot;);
          }
  
  
          static async Task Transaction(string connectionString) {
              var client = new MongoClient(connectionString);
  
              var database = client.GetDatabase(&quot;TestDB&quot;);
  
              // the same exception.
  
              var collection = database.GetCollection&lt;TestData&gt;(nameof(TestData));
              using (var session = await client.StartSessionAsync()) {
                  session.StartTransaction();
                  try {
                      await collection.InsertOneAsync(new TestData(Guid.NewGuid().ToString(), &quot;Test2&quot;, new DateTimeOffset(DateTime.Now)));
  
                      await session.CommitTransactionAsync();
                  }
                  catch (Exception ex) {
                      await session.AbortTransactionAsync();
                  }
              }
  
              Console.WriteLine(&quot;done transaction.&quot;);
          }
      }
  
      public class TestData {
          public string Id { get; set; }
          public string Name { get; set; }
          public DateTimeOffset CreatedAt { get; private set; }
  
          public TestData(string id, string name, DateTimeOffset createdAt) {
              Id = id;
              Name = name;
              CreatedAt = createdAt;
          }
      }
  }
  </code></pre>
  <p>Has anyone a solution for using MongoDB Replica Set inside Kubernetes and accessing it without any exceptions from outside?</p>
  <p>I would be very thankful for helping us.</p>