Kubernetes — Node + MongoDB Communication Notes

Why Separate Pods (Not One Pod with Multiple Containers):

If both node and mongo are in one pod:

Solution → Separate pods, communicate via Services


The Full Picture — Flow First

Node Pod                    Mongo Pod
(port 3000)                 (port 27017)
     |                           |
     |                           |
service-node-app          service-mongodb
(8080→3000)               (27017→27017)
     |                           |
     └──── talk via DNS ─────────┘
           "service-mongodb:27017"

Node pod never talks to mongo pod directly. It calls service-mongodb by name — the Service receives the request and routes it to the mongo pod. If mongo pod restarts and gets a new IP, the Service still works — node app is unaffected.


How Communication Actually Happens (Step by Step)

1. Node pod starts
         ↓
2. Kubernetes injects env vars from ConfigMap      (node code has mongo connect in index.js)
   MONGO_HOST = "service-mongodb"
   MONGO_PORT = "27017"
         ↓
3. index.js runs → mongoose.connect() called once
         ↓
4. Mongoose opens TCP connection to "service-mongodb:27017"
         ↓
5. Kubernetes DNS resolves "service-mongodb" → mongo pod IP
         ↓
6. Connection established — stays open permanently
         ↓
7. Every Email.find() / newEmail.save() reuses this open connection

mongoose.connect() is like dialing once and keeping the line open — all queries after that just use the same connection.


File by File — Role + Full Code


mongo-config.yml — ConfigMap

Role: Just a key-value store. No pods, no containers. Stores mongo connection details so nothing is hardcoded in the image.