I'm trying to connect from Google Cloud Run to MongoDB using VPC and peer networking but I can't seem to establish a connection. The goal is to be able to connect from Cloud Run to Atlas while only allowing a certain IP range.
My setup is:
I have taken the following steps:
Create a VPC on the Google Cloud side following instructions from https://cloud.google.com/vpc/docs/using-vpc.
Setup a network peering between my VPC and the MongoDB Atlas VPC: https://docs.atlas.mongodb.com/security-vpc-peering/
Setup serverless VPC access using a connector: https://cloud.google.com/vpc/docs/configure-serverless-vpc-access
Re-deployed cloud run container using the connector above: https://cloud.google.com/run/docs/configuring/connecting-vpc
Added the CIDR range from step 3 to the whitelist in MongoDB atlas and removed the previous open range 0.0.0.0/0.
All steps succeed (green dots etc) but when I try to connect after step 5 the connection fails. What am I missing?
To connect to a MongoDB, retrieve the hostname and port information from Cloud Manager and then use a MongoDB client, such as mongosh or a MongoDB driver, to connect. To connect to a cluster, retrieve the hostname and port for the mongos process.
Solved this so answering my own question. Turns out the approach outlined in the question does work. I was missing two things:
You need to change the MongoDB connection string to the private connection string. You can retrieve this by clicking on "Connect" under "Clusters" in the MongoDB dashboard. This is as far as I could see not documented anywhere in the MongoDB peer networking guide.
Whitelist the CIDR range from both the VPC itself (step 1) and the CIDR range from the serverless connector (step 3) in the MongoDB Atlas network settings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With