How do you connect to MongoDB Atlas from Google Cloud Run when using VPC and peer networking?

Viewed 2440

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:

  • MongoDB Atlas running on Google Cloud.
  • A Google Cloud Run container running a NodeJS server on the same region as MongoDB atlas (although that shouldn't matter as far as I can tell).

I have taken the following steps:

  1. Create a VPC on the Google Cloud side following instructions from https://cloud.google.com/vpc/docs/using-vpc.

  2. Setup a network peering between my VPC and the MongoDB Atlas VPC: https://docs.atlas.mongodb.com/security-vpc-peering/

  3. Setup serverless VPC access using a connector: https://cloud.google.com/vpc/docs/configure-serverless-vpc-access

  4. Re-deployed cloud run container using the connector above: https://cloud.google.com/run/docs/configuring/connecting-vpc

  5. 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?

1 Answers

Solved this so answering my own question. Turns out the approach outlined in the question does work. I was missing two things:

  1. 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.

  2. 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.

Related