Ewan Valentine
Ewan Valentine

Reputation: 3931

No connection error when attempting to connect to a stateful set Mongodb Kubernetes deployment

I have the following service...

apiVersion: v1
kind: Service
metadata:
  name: mongo
  labels:
    app: mongo
spec:
  ports:
  - name: mongo
    port: 27017
  clusterIP: None
  selector:
    app: mongo

And the following stateful set...

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mongo
spec:
  serviceName: mongo
  selector:
    matchLabels:
      app: mongo
  replicas: 3
  template:
    metadata:
      labels:
        app: mongo
    spec:
      terminationGracePeriodSeconds: 10
      containers:
        - name: mongo
          image: mongo
          command:
            - mongod
            - "--replSet"
            - rs0
            - "--smallfiles"
            - "--noprealloc"
          ports:
            - name: mongo
              containerPort: 27017
        - name: mongo-sidecar
          image: cvallance/mongo-k8s-sidecar
          env:
            - name: "VERSION"
              value: "2"
            - name: MONGO_SIDECAR_POD_LABELS
              value: "role=mongo"

However, my code can't make a connection, using the url mongo:27017. I've tried connecting to mongo, mongo-0.mongo:27017, loads of others. If I exec into a container and run $ nslookup mongo I get...

Name:      mongo
Address 1: 10.1.0.80 mongo-0.mongo.default.svc.cluster.local
Address 2: 10.1.0.81 mongo-1.mongo.default.svc.cluster.local
Address 3: 10.1.0.82 mongo-2.mongo.default.svc.cluster.local

Hitting $ curl mongo:27017 or $ telnet mongo 27017 gives me a connection refused error.

Upvotes: 2

Views: 966

Answers (2)

stacksonstacks
stacksonstacks

Reputation: 9313

Add bind_ip to command:

      command:
        - mongod
        - "--replSet"
        - rs0
        - "--smallfiles"
        - "--noprealloc"          
        - "--bind_ip"
        - "0.0.0.0"

This option tells the monogodb daemon to listen on all IPv4 addresses, rather than the default of localhost.

Upvotes: 6

Ewan Valentine
Ewan Valentine

Reputation: 3931

Okay so I fixed this, it was a case of setting the bind_ip=0.0.0.0, but it was also that I had to change the selector in my service to role: mongo instead if app: mongo. Then in my deployment I had to include role: mongo in my metadata, like...

template:
    metadata:
      labels:
        app: mongo
        role: mongo

Upvotes: 1

Related Questions