Unable to create mongodb replica set on kubernetes pod

10/24/2019

I am trying to create MongoDB replica-set on kubernetes. I have a namespace 'global' and I have deployed mongodb in that and I have exposed MongoDB pod using a headless service.

Deployment file looks like-

apiVersion: v1
kind: Service
metadata:
  name: mongodb
  namespace: global
spec:
  selector:
    app: mongodb
  ports:
  - port: 27017
  clusterIp: None

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mongodb
  namespace: global
spec:
  selector:
    matchLabels:
      app: mongodb
  template:
    metadata:
      labels:
        app: mongodb
    spec:
      containers:
      - name: mongodb
        image: mongo:4.2.1
        args: ["mongod","--replSet", "rs0","--bind_ip","mongodb.global.svc.cluster.local:27017, localhost"]
        resources:
          limits:
            memory: "128Mi"
            cpu: "500m"
        ports:
        - containerPort: 27017

Now if you look at the args I have bind mongodb.global.svc.cluster.local:27017 and localhost to mongo pod, which basically are the interfaces on which mongo would listen. Here I am supposing that -- mongodb.global.svc.cluster.local:27017 this address would resolve to pod IP because [service_name].[namespace].svc.cluster.local is supposed to resolve to pod IP according to kubernetes documentation (in case of headless service which is the case here).

To initiate the replica (According to the documentation), I must exec into the pod and run the following through mongo shell

rs.initiate(
   {
      _id: "rs0",
      version: 1,
      members: [
         { _id: 0, host : "mongodb.global.svc.cluster.local:27017" },
      ]
   }
)

But this throws the following error

{
        "operationTime" : Timestamp(0, 0),
        "ok" : 0,
        "errmsg" : "No host described in new configuration 1 for replica set rs0 maps to this node",
        "code" : 93,
        "codeName" : "InvalidReplicaSetConfig",
        "$clusterTime" : {
                "clusterTime" : Timestamp(0, 0),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        }
}

I don't know what am I doing wrong, the host is supposed to be easily discovered but it's not happening.

-- Vishal Tewatia
kubernetes
mongodb
mongodb-replica-set

1 Answer

10/25/2019

I see 2 options here:

  1. Run hostname() and myPort() in the mongo shell to make sure it matches the value you are using for 'host' in the initiate command

  2. Run rs.initiate() without any options, it will by default use the replica set name from the command line option, version 1, and its own host:port

-- Joe
Source: StackOverflow