0

I have an applications Docker image which starts a mongodb instance on a random port. When I create a kubernetes Pod with application image; application gets successfully initialized and a mongodb instance gets up on a random port as localhost:port without any error.

However, when I create a Kubernetes Deployment; the same application initialization fails inside the container with error "mongodb can not be started as localhost:port can not be accessed".

If anyone can explain, why application initialization is failing with K8-Deployment but not with K-8Pod? And, How can I resolve this problem?

apiVersion: apps/v1
kind: Pod
metadata:
  name: my-app
spec:
  containers:
  - name: my-app
    image: my-app:v1
    ports:
    - containerPort: 8888 # Apps exposed port

---

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
  labels:
    app: my-dep
spec:
  replicas: 2
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-app
        image: my-app:v1
        ports:
        - containerPort: 8888 # Apps exposed port

Thanks

Jonas
  • 121,568
  • 97
  • 310
  • 388
Jaraws
  • 581
  • 1
  • 7
  • 24
  • Can you provide actual source code (like the Dockerfile and YAML artifacts) and the actual error message? "Random port" and "localhost" both sound kind of unusual in a Kubernetes context. – David Maze Dec 13 '19 at 20:07
  • @David, the app code has a logic to randomly identify an available port on host machine and get the mongodb server up on that port, later app loads data to that mongodb server. In case of K8-Deployment, application goes to start the mongodb server at localhost:[random-port] and it fails with error localhost:random Port can not be accessed. However, the same works fine in case of K8-Pod. – Jaraws Dec 13 '19 at 20:22
  • I'd expect to ordinarily run something like MongoDB in a StatefulSet, and have it accessible via a Service. `localhost` usually means "this container" or "this pod", and not something else on the host system. – David Maze Dec 13 '19 at 20:25
  • Added yaml artifacts for Pod and Deployment. – Jaraws Dec 13 '19 at 20:34

1 Answers1

1

Instead of listening on localhost:port, you should try configure MongoDB to listening on 0.0.0.0:port. This has helped me when having a similar issue with another app.

Configure MongoDB to listen to all interfaces

Your mongod.conf

# /etc/mongod.conf

# Listen to local interface only. Comment out to listen on all interfaces.
bind_ip = 127.0.0.1

change to this

# /etc/mongod.conf

# Listen to local interface only. Comment out to listen on all interfaces.
# bind_ip = 127.0.0.1
Jonas
  • 121,568
  • 97
  • 310
  • 388