<p>I have a flask app with a mongodb database that I am attempting to deploy on minikube.</p>
<p>I have containerized both applications and determined that they work without orchestration.</p>
<p>I make sure to start mongodb before flask.</p>
<p>However, I get the following error when running in kubernetes.
kubectl logs flaskweb-deployment-7f6775bc8f-7q72j</p>
<pre><code>Traceback (most recent call last):
  File &quot;run.py&quot;, line 1, in &lt;module&gt;
    from app import web_app, socketio
  File &quot;/code/app/__init__.py&quot;, line 18, in &lt;module&gt;
    from .main import main as main_blueprint
  File &quot;/code/app/main/__init__.py&quot;, line 5, in &lt;module&gt;
    from . import routes, events
  File &quot;/code/app/main/routes.py&quot;, line 8, in &lt;module&gt;
    from .models import eInstance, eMessage
  File &quot;/code/app/main/models.py&quot;, line 24, in &lt;module&gt;
    if eInstance.objects().first() is None:
  File &quot;/usr/local/lib/python3.8/dist-packages/mongoengine/queryset/manager.py&quot;, line 38, in __get__
    queryset = queryset_class(owner, owner._get_collection())
  File &quot;/usr/local/lib/python3.8/dist-packages/mongoengine/document.py&quot;, line 223, in _get_collection
    if cls._meta.get(&quot;auto_create_index&quot;, True) and db.client.is_primary:
  File &quot;/usr/local/lib/python3.8/dist-packages/pymongo/mongo_client.py&quot;, line 1088, in is_primary
    return self._server_property('is_writable')
  File &quot;/usr/local/lib/python3.8/dist-packages/pymongo/mongo_client.py&quot;, line 889, in _server_property
    server = self._topology.select_server(
  File &quot;/usr/local/lib/python3.8/dist-packages/pymongo/topology.py&quot;, line 244, in select_server
    return random.choice(self.select_servers(selector,
  File &quot;/usr/local/lib/python3.8/dist-packages/pymongo/topology.py&quot;, line 202, in select_servers
    server_descriptions = self._select_servers_loop(
  File &quot;/usr/local/lib/python3.8/dist-packages/pymongo/topology.py&quot;, line 218, in _select_servers_loop
    raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: 10.97.8.16:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: &lt;TopologyDescription id: 6187e39295442839a2d95a49, topology_type: Single, servers: [&lt;ServerDescription ('10.97.8.16', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('10.97.8.16:27017: [Errno 111] Connection refused')&gt;]&gt;
</code></pre>
<p>I have looked at all of the posts I can find pertaining to this issue but can't match any of those problems with my implementation.</p>
<p>Dockerfiles
mongodb</p>
<pre><code>FROM ubuntu:18.04
RUN apt update; apt install -y gnupg2 
RUN apt install -y software-properties-common

# Installation
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4

RUN add-apt-repository 'deb [arch=amd64] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.0 multiverse'

RUN apt-get update &amp;&amp; apt install -y mongodb-org

RUN mkdir /data

RUN mkdir /data/db


# Start db
#RUN mongod --bind_ip=0.0.0.0 &amp;

EXPOSE 27017
# Set entrypoint
ENTRYPOINT [&quot;usr/bin/mongod&quot;, &quot;--bind_ip=0.0.0.0&quot;]
</code></pre>
<p>python flask</p>
<pre><code>FROM ubuntu:latest
RUN apt update; apt install -y gnupg2
WORKDIR /code
COPY . /code/
RUN apt install -y python3-pip
RUN pip3 install -r requirements.txt
ENV PYTHONPATH /code
EXPOSE 8080
ENTRYPOINT [ &quot;python3&quot; ]
CMD [ &quot;run.py&quot; ]
</code></pre>
<p>yaml files for deployment and service</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: mongodb-deployment
  labels:
    app: mongodb
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mongodb
  template:
    metadata:
      labels:
        app: mongodb
    spec:
      containers:
      - name: mongodb
        image: mongodb:v1
        imagePullPolicy: Never
        ports:
        - containerPort: 27017
      volumes:
            - name: mongo-persistent-storage
              mountPath: /data/db
      volumes:
        - name: mongo-persistent-storage
</code></pre>
<p>serviceDB.yaml</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
  labels:
    name: mongodb-service
  name: mongodb-service
spec:
  ports:
    - port: 27017
      targetPort: 27017
  selector:
    app: mongodb
</code></pre>
<p>webserver-deploy.yaml</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: flaskweb-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: flaskweb
  template:
    metadata:
      labels:
        app: flaskweb
    spec:
      containers:
        - name: flaskweb
          image: flaskweb:v1
          ports:
            - containerPort: 8080
</code></pre>
<p>serviceWEB.yaml</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
  name: flaskweb-service
spec:
  selector:
        app: flaskweb
  type: NodePort
  ports:
    - protocol: &quot;TCP&quot;
      port: 8080
      targetPort: 8080
      nodePort: 30100
</code></pre>
<p>kubectl get pods</p>
<pre><code>NAME                                   READY   STATUS    RESTARTS      AGE
flaskweb-deployment-7f6775bc8f-7q72j   0/1     Error     1 (40s ago)   74s
flaskweb-deployment-7f6775bc8f-lpwlz   0/1     Error     1 (40s ago)   74s
flaskweb-deployment-7f6775bc8f-pvnjz   0/1     Error     1 (40s ago)   74s
mongodb-deployment-867998dcff-786tv    1/1     Running   0             6m29s

NAME                                   READY   STATUS             RESTARTS       AGE
flaskweb-deployment-7f6775bc8f-7q72j   0/1     CrashLoopBackOff   9 (94s ago)    27m
flaskweb-deployment-7f6775bc8f-lpwlz   0/1     CrashLoopBackOff   9 (85s ago)    27m
flaskweb-deployment-7f6775bc8f-pvnjz   0/1     CrashLoopBackOff   9 (111s ago)   27m
mongodb-deployment-867998dcff-786tv    1/1     Running            0              33m
</code></pre>
<p>kubectl get services</p>
<pre><code>NAME               TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
flaskweb-service   NodePort    10.105.225.55   &lt;none&gt;        8080:30100/TCP   2s
kubernetes         ClusterIP   10.96.0.1       &lt;none&gt;        443/TCP          23h
mongodb-service    ClusterIP   10.97.8.16      &lt;none&gt;        27017/TCP        24m
</code></pre>
<p>mongodb settings in config.py</p>
<pre><code>MONGODB_SETTINGS = {'db': 'mongodb', 'host': '10.97.8.16', 'port': 27017} 
</code></pre>
<p>kubectl describe pod flaskweb-deployment-7f6775bc8f-7q72j</p>
<pre><code>Name:         flaskweb-deployment-7f6775bc8f-7q72j
Namespace:    default
Priority:     0
Node:         minikube/192.168.49.2
Start Time:   Sun, 07 Nov 2021 14:31:31 +0000
Labels:       app=flaskweb
              pod-template-hash=7f6775bc8f
Annotations:  &lt;none&gt;
Status:       Running
IP:           172.17.0.6
IPs:
  IP:           172.17.0.6
Controlled By:  ReplicaSet/flaskweb-deployment-7f6775bc8f
Containers:
  flaskweb:
    Container ID:   docker://93d1a5c0dfb69feadb8b1c252a3ad4635342e5117c2814f838e651cf0e9f13d9
    Image:          flaskweb:v1
    Image ID:       docker://sha256:eaf719a9964b4de784f2a56951e9d058e41f7201a7db25d26a5100539841e25b
    Port:           8080/TCP
    Host Port:      0/TCP
    State:          Waiting
      Reason:       CrashLoopBackOff
    Last State:     Terminated
      Reason:       Error
      Exit Code:    1
      Started:      Sun, 07 Nov 2021 14:57:17 +0000
      Finished:     Sun, 07 Nov 2021 14:57:49 +0000
    Ready:          False
    Restart Count:  9
    Environment:    &lt;none&gt;
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-hchq9 (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             False 
  ContainersReady   False 
  PodScheduled      True 
Volumes:
  kube-api-access-hchq9:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       &lt;nil&gt;
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              &lt;none&gt;
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type     Reason     Age                   From               Message
  ----     ------     ----                  ----               -------
  Normal   Scheduled  29m                   default-scheduler  Successfully assigned default/flaskweb-deployment-7f6775bc8f-7q72j to minikube
  Normal   Created    25m (x5 over 29m)     kubelet            Created container flaskweb
  Normal   Started    25m (x5 over 29m)     kubelet            Started container flaskweb
  Normal   Pulled     9m3s (x9 over 29m)    kubelet            Container image &quot;flaskweb:v1&quot; already present on machine
  Warning  BackOff    3m58s (x94 over 27m)  kubelet            Back-off restarting failed container
</code></pre>
<p>Edit:
I matched the selector using app instead of name in the service yaml.</p>
<p>Still getting the following errors:</p>
<pre><code>Traceback (most recent call last):
  File &quot;run.py&quot;, line 1, in &lt;module&gt;
    from app import web_app, socketio
  File &quot;/code/app/__init__.py&quot;, line 18, in &lt;module&gt;
    from .main import main as main_blueprint
  File &quot;/code/app/main/__init__.py&quot;, line 5, in &lt;module&gt;
    from . import routes, events
  File &quot;/code/app/main/routes.py&quot;, line 8, in &lt;module&gt;
    from .models import eInstance, eMessage
  File &quot;/code/app/main/models.py&quot;, line 24, in &lt;module&gt;
    if eInstance.objects().first() is None:
  File &quot;/usr/local/lib/python3.8/dist-packages/mongoengine/queryset/manager.py&quot;, line 38, in __get__
    queryset = queryset_class(owner, owner._get_collection())
  File &quot;/usr/local/lib/python3.8/dist-packages/mongoengine/document.py&quot;, line 223, in _get_collection
    if cls._meta.get(&quot;auto_create_index&quot;, True) and db.client.is_primary:
  File &quot;/usr/local/lib/python3.8/dist-packages/pymongo/mongo_client.py&quot;, line 1088, in is_primary
    return self._server_property('is_writable')
  File &quot;/usr/local/lib/python3.8/dist-packages/pymongo/mongo_client.py&quot;, line 889, in _server_property
    server = self._topology.select_server(
  File &quot;/usr/local/lib/python3.8/dist-packages/pymongo/topology.py&quot;, line 244, in select_server
    return random.choice(self.select_servers(selector,
  File &quot;/usr/local/lib/python3.8/dist-packages/pymongo/topology.py&quot;, line 202, in select_servers
    server_descriptions = self._select_servers_loop(
  File &quot;/usr/local/lib/python3.8/dist-packages/pymongo/topology.py&quot;, line 218, in _select_servers_loop
    raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: 10.97.8.16:27017: timed out, Timeout: 30s, Topology Description: &lt;TopologyDescription id: 61880d44d1e4d98ec7db8557, topology_type: Single, servers: [&lt;ServerDescription ('10.97.8.16', 27017) server_type: Unknown, rtt: None, error=NetworkTimeout('10.97.8.16:27017: timed out')&gt;]&gt;
</code></pre>
<p>FINAL EDIT:
The system was running out of resources.  docker system prune helped.</p>

Ozixic
<p>The issue here is with the configuration of your service for mongodb.</p>
<pre><code>~$ kubectl explain service.spec.selector
KIND:     Service
VERSION:  v1

FIELD:    selector &lt;map[string]string&gt;

DESCRIPTION:
     Route service traffic to pods with label keys and values matching this
     selector. If empty or not present, the service is assumed to have an
     external process managing its endpoints, which Kubernetes will not modify.
     Only applies to types ClusterIP, NodePort, and LoadBalancer. Ignored if
     type is ExternalName. More info:
     https://kubernetes.io/docs/concepts/services-networking/service/
</code></pre>
<p>as you can see fro the above, the selector uses pod label keys and values to know which pods to service.</p>
<p>If you run the command</p>
<pre><code>~$ kubectl get endpoints mongodb-service
</code></pre>
<p>you should see that there are no endpoints behind your service. The reason is that your service is not properly selecting the pods. Currently you have this selector:</p>
<pre><code>selector:
  name: mongodb
</code></pre>
<p>but your pods are labeled differently:</p>
<pre><code>labels:
  app: mongodb
</code></pre>
<p>Simply by changing the <code>name</code> to <code>app</code> within the manifest for mongodb service, should take care of this issue.</p>
<p>Another thing I wanted to bring your attention to is that you are using the statically set ip address of the service in your mongodb configuration in flask.</p>
<pre><code>MONGODB_SETTINGS = {'db': 'mongodb', 'host': '10.97.8.16', 'port': 27017} 
</code></pre>
<p>this is not a good approach. Better way to do it would be to use the service name and let kubedns take care of the name resolution.</p>
