I am running several NodeJS v16.16 applications in Google Cloud Run. These applications connect to a Google Cloud SQL server and a MongoDB Atlas cluster through a VPC connector with a static IP address that is whitelisted for both the MongoDB Atlas cluster and the SQL server.
We are experiencing intermittent connection failures to these databases when new instances are started as if the IP address is not whitelisted. For connections using mongoose we get an MongooseServerSelectionError: Server selection timed out after 30000 ms at NativeConnection.Connection.openUri
. And for connections using sequalize we get an Error connecting MySQL: SequelizeConnectionError: connect ETIMEDOUT
Things I have established by testing, logging and checking configurations:
https://api.ipify.org?format=json
one line before connecting to the databases and logged the results.The intermittent connection failures are an issue as when this happens an instance fails to start and the user gets a 503 error as a response.
Versions:
We have found the issue. We were initializing the connection to our database right after we started listening for incoming requests (example below). We changed this to connect to the database before listening for requests and haven't had an error since. Why exactly this is happening is unknown but I figure it has something to do with the processes that Google Cloud Run uses to prepare an instance for handling requests.
Old code:
// start the Express server
app.listen(port, async () => {
database.connect();
console.log("Server started!");
});
New code:
database.connect().then(() => {
// start the Express server
app.listen(port, async () => {
console.log("Server started!");
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.