Fix: keep retrying MongoDB connection in background if initial attempts fail
This commit is contained in:
1 parent
1b9f10fb55
commit
a75c4bdec1
1 file changed
+21
-2
+21
-2
@@ -36,8 +36,27 @@ async function connectDB() {
|
||||
}
|
||||
}
|
||||
|
||||
console.error('[MongoDB] All connection attempts failed. Backend cannot serve dashboard data.');
|
||||
// Do NOT exit — allow health check endpoint to remain available
|
||||
console.error('[MongoDB] Initial connection attempts failed. Scheduling background reconnect every 10s...');
|
||||
// Keep retrying in the background so Docker Swarm container restarts never leave backend permanently disconnected
|
||||
const timer = setInterval(async () => {
|
||||
if (mongoose.connection.readyState >= 1) {
|
||||
clearInterval(timer);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
console.log('[MongoDB] Background reconnect attempt...');
|
||||
await mongoose.connect(MONGODB_URI, {
|
||||
serverSelectionTimeoutMS: 10000,
|
||||
connectTimeoutMS: 10000,
|
||||
});
|
||||
console.log('[MongoDB] ✓ Background reconnect succeeded to', MONGODB_URI);
|
||||
clearInterval(timer);
|
||||
const { logCapacityStats } = require('./capacityTracker');
|
||||
logCapacityStats('[MongoDB]').catch(err => console.warn('[MongoDB] Capacity log failed:', err.message));
|
||||
} catch (err) {
|
||||
console.error(`[MongoDB] ✗ Background reconnect failed: ${err.message}`);
|
||||
}
|
||||
}, 10000);
|
||||
}
|
||||
|
||||
module.exports = connectDB;
|
||||
Reference in new issue
Block a user