First for my question, I need to talk a bit about my enviroments:
Google Basic Setup: 1x f1-micro instance with 3 nodes
Kubernetes Setup: nginx-ingress-controller, cert-manager, 1-backend service with deployment, 1-frontend service with deployment.
Mongo Atlas Setup: 3-replicaSet
Setup should not be a prolbem, but It might give some scenario feelings.
OK, Let comes to the issue, my Nodejs backend use the following url to connect to MonglAtlas database:
MONGODB_URI=mongodb+srv://username:pwd@mongotoken-66gqa.gcp.mongodb.net/test?retryWrites=true
IP Whitelist is my static public IP that use nginx-ingress to route. Let me define my.domain
to my frontend webpage, and my.domain/api/
to backend api.
Everything is fine when IP Whitelist is ALLOW ACCESS FROM ANYWHERE, and backend could connect to MongoAtlas DB for no doubt.
But when I delete that option, and add the IP that matched with my.domain
(double check, I ping my.domain
is absolutely same IP), and then backend could not find the database with following error:
MongoNetworkError: connection 4 to closed https....
If there is something missing infos, please let me know. Any advice is appreciated!
Another suspected is that I got 1 static IP and 3 ephemeral IP in VPC network. I guess It means 3 node with loadbalancer IP. If the backend use ephemeral IP to connect to MongoAtlas backend, I must check the pod that in which nodes and make that node static, but this make no sense for Kubernetes. I hope there is another solution :(
Ingress and egress traffic goes different ways.
When you connect to ingress, your traffic goes thru load balancer with static IP (I hope you use ingress with service type "Load Balancer).
When you connect from cluster to any external resource, you connect directly from the node when your container works, so you need to whitelist addresses of your nodes on Atlas to allow connections from them.
The solution I used is NAT. The concept is to establish 1- Google Compute Engine Instance as NAT Gateway, and mapping all the egress to a static ip. Oh, the most important is all the steps above do not need to manual config, just follow the documentation, and everything should be work as expected.
If there is a STATIC_ADDRESS QUOTA problem, you could change your ZONE and REGION to any QUOTA-remained area. For my case, us-central as NAT and us-west as Original Service.