eins
eins

Reputation: 43

Cannot connect to mongodb from another pod in kubernetes cluster

There is a running a kubernetes cluster with a Web server, a Redis server, and a MongoDB server which is using official docker image: mongo:4.4.0

I exposed MongoDB server with name mongodb and Redis server with name redis:

NAME      TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)     AGE
backend   ClusterIP   172.19.14.124   <none>        7001/TCP    15h
mongodb   ClusterIP   172.19.10.24    <none>        27017/TCP   15h
redis     ClusterIP   172.19.6.203    <none>        6379/TCP    15h

Now, from backend webserver, I cannot connect to MongoDB server with mongo --host mongodb but connect to Redis using redis -h redis works.

Then checked by kubectl exec -it mongodb-5f4bd8c8d-hbsfx -- bash:

  1. mongo mongodb works, it connected to 127.0.0.1

  2. mongo 172.19.10.24 fail, it results in
    Error: couldn't connect to server 172.19.10.24:27017, connection attempt failed: SocketException: Error connecting to 172.19.10.24:27017 :: caused by :: Connection refused :

  3. ping mongodb works well.

From the ps result, it already bind all:

mongodb 1 0.2 2.5 1588248 98272 ? Ssl Aug20 2:02 mongod --bind_ip_all

What's wrong and how to fix it? thx.


update

command ss result from pod

LISTEN     0        0                  0.0.0.0:27017            0.0.0.0:*        users:(("mongod",pid=1,fd=9))
apiVersion: v1
kind: Service
metadata:
  namespace: tabby
  name: mongodb
  labels:
    app: mongodb
spec:
  ports:
  - port: 27017
    targetPort: 27017
  selector:
    name: mongodb
---
apiVersion: apps/v1
kind: Deployment
metadata:
  namespace: tabby
  name: mongodb
  labels:
    app: mongodb
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mongodb
  template:
    metadata:
      labels:
        app: mongodb
    spec:
      imagePullSecrets:
      - name: regcred
      containers:
      - name: mongodb
        image: mongo:4.4.0
        ports:
        - containerPort: 27017
        volumeMounts:
        - name: data
          mountPath: /data/db
      volumes:
      - name: data
        emptyDir: {}

Upvotes: 1

Views: 3813

Answers (1)

Arghya Sadhu
Arghya Sadhu

Reputation: 44687

The service selector has name: mongodb but deployment has got app: mongodb label. Because of this mismatch service is not selecting the pods. If you check the Endpoints section of the service using kubectl describe svc mongodb -n tabby you will not see any Pod IPs because of the above reason.

Change the service as follows.

apiVersion: v1
kind: Service
metadata:
  namespace: tabby
  name: mongodb
  labels:
    app: mongodb
spec:
  ports:
  - port: 27017
    targetPort: 27017
  selector:
    app: mongodb

Upvotes: 1

Related Questions