If both node and mongo are in one pod:
Solution → Separate pods, communicate via Services
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.
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.
mongo-config.yml — ConfigMapRole: Just a key-value store. No pods, no containers. Stores mongo connection details so nothing is hardcoded in the image.