Connect to MongoDB Atlas from Google CloudRun

Hi,

I’m trying to connect to my M0 cluster from CloudRun application. Connecting from my local machine works fine, however when connecting from GCP I’m receiving an error:

com.mongodb.MongoTimeoutException: Timed out while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=REPLICA_SET, servers=[{address=xxxx.mongodb.net:27017, type=UNKNOWN, state=CONNECTING}, {address=xxxx.mongodb.net:27017, type=UNKNOWN, state=CONNECTING}, {address=xxxx.mongodb.net:27017, type=UNKNOWN, state=CONNECTING}]
	at com.mongodb.internal.connection.BaseCluster.createAndLogTimeoutException(BaseCluster.java:392)
	at com.mongodb.internal.connection.BaseCluster.handleServerSelectionRequest(BaseCluster.java:293)
	at com.mongodb.internal.connection.BaseCluster.access$800(BaseCluster.java:85)
	at com.mongodb.internal.connection.BaseCluster$WaitQueueHandler.run(BaseCluster.java:475)
	at java.base/java.lang.Thread.run(Thread.java:1583)

I added 0.0.0.0/0 entry in network configuration. I use kotlin driver (latest)

Hi Marcin, welcome!

I’m wondering if the connection string is not making it to the environment where your app launches in GCP… How are you storing and accessing your connection string in your app?

To configure environment variables for your Google Cloud Run service, you’ll use the app.yaml file if you’re deploying with Google App Engine or set environment variables directly in the Cloud Run service if you’re using that platform.

Here’s how I do it for Google App Engine:

Creating and Storing Environment Variables in app.yaml

In your app.yaml file, you can specify environment variables under the env_variables key. This file is where you define your app’s deployment settings, and the environment variables you add here will be available to your application at runtime.

Here’s an example of what it might look like:

runtime: java11  # or other runtime you're using, like python, node, etc.

env_variables:
  MONGO_URI: "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority"
  FOO: "bar"

If you’re using Google Cloud Run, environment variables are set when you deploy the service. You can use the Google Cloud CLI or set them directly in the UI.

1. Using the Google Cloud CLI:

gcloud run deploy --image gcr.io/your-project/your-image \
  --set-env-vars MONGO_URI="mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority"

2. In the Cloud Console:

  • Go to the Cloud Run service page.
  • Click Edit & Deploy New Revision for your service.
  • Under Variables & Secrets, add your environment variables there.

Also - If possible, store secrets securely using Google Secret Manager and expose/access them as env variables at runtime.

Let us know if this helped…
Mike

I just hardcoded the connection string