I use docker-compose
on aws ec2
to build node.js express
to connect to mongodb atlas
.I have created a connection whitelist
and can connect smoothly.But, the db connection will be disconnected suddenly, and the disconnection time is irregular. Sometimes it is a week apart, and sometimes it is disconnected within a day.
erroe message:
MongoTimeoutError: Server selection timed out after 10000 msat Timeout._onTimeout (/app/node_modules/mongodb-core/lib/sdam/topology.js:773:16)at listOnTimeout (node:internal/timers:569:17)at process.processTimers (node:internal/timers:512:7) {[Symbol(mongoErrorContextSymbol)]: {}}
My current solution is to write an API to reconnect the DB through the API when the DB is found to be disconnected. As long as it is reconnected, it can successfully reconnect to the DB without restarting Docker(node.js), which means that the server is not faulty and there is problem in db connection.
The following is an example of my connection to the db:
mongoLink = 'mongodb://'+dbConfig.host+':'+dbConfig.port+'/'+ dbConfig.dbName;mongoose.connect(mongoLink, { useNewUrlParser: true, useUnifiedTopology: true }).then(() => { console.log('memo-today db connented'); }).catch((e) => { console.log(e); console.log("connection failed!"); });
Even if it can be solved by automatically detecting the db disconnection and automatically starting the reconnection, it does not seem to be a good method. There must be some connection problem with the db connection.
The following solution suggests that I add parameters ?directConnection=true
, but it seems not suitable for use in a production environment.
MongoDB replica set is a group of connected instances that store the same set of data. This configuration provides data redundancy and high data availability. By enabling directConnection=true, you are losing this feature.