How to port forward to Primary in Kubernetes Cluster

I want to port forward to my Primary in the ReplicaSet on my Kubernetes Cluster. This is how I am doing it now and it always connects to the secondary:

kubectl port-forward svc/percona-db-psmdb-db-rs0 -n psmdb 27017:27017

Then when I connect:

mongosh 'mongodb://user:pass@localhost:27017/ms_user?ssl=false'

Connecting to:		mongodb://<credentials>@localhost:27017/user?ssl=false&directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.5.4
Using MongoDB:		4.4.10-11
Using Mongosh:		1.5.4

Then when I want to do operations I get:

rs0 [direct: secondary] ms_user> db.users.drop()
MongoServerError: not primary
1 Like


I wonder if the namespace flag you are using should be before the subcommand, like:

kubectl -n psmdb port-forward svc/percona-db-psmdb-db-rs0 27017:27017

I don’t have a test instance at hand now, so please test this and let me know if it worked. Otherwise, I can spin something up and test.

1 Like

Also, what do you get from kubectl -n namespace get services?

1 Like

Hi @anon17965173 ,
How do you install database and which services do you have setup?
I see you use helm if I’m not mistaking, this is what I did and it seems to work for me, but probably I did something different than in your setup.

Install DB:

helm install operator percona/psmdb-operator --namespace helm-test
helm install psmdb-db percona/psmdb-db --namespace helm-test --set sharding.enabled=false --set image.tag=4.4.16-16

so in my setup sharding is disabled and this is the service which is setup and to which I port-forward:

psmdb-db-rs0   ClusterIP   None         <none>        27017/TCP   7m51s

# port forwarding
$ kubectl port-forward svc/psmdb-db-rs0 -n helm-test 27017:27017
Forwarding from -> 27017
Forwarding from [::1]:27017 -> 27017

When I connect it seems to be always primary:

$ mongosh 'mongodb://<credentials>@localhost:27017/admin?ssl=false'
Current Mongosh Log ID: 63aec47a83658493db6015b4
Connecting to:          mongodb://<credentials>@localhost:27017/admin?ssl=false&directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.1
Using MongoDB:          4.4.16-16
Using Mongosh:          1.6.1

rs0 [direct: primary] admin> use test;
switched to db test

rs0 [direct: primary] test> db.korisnici.insert({ name: "Tomislav" })
  acknowledged: true,
  insertedIds: { '0': ObjectId("63aec48d83658493db6015b5") }