Docker randomly cannot connect to random containers after restart

Hello guys, I have just started with docker.

I have 3 nodes on Docker swarm running nodejs application (mode:global), and I have 3 mongodb database replica standalone, which also joined the swarm via network:overlay.

They databases are all accessible via service names.

My Problem

I am able to connect to all the mongo databases from both the app, and with mongo client at first, via the service names.

However, if I restart any of the servers, randomly one or two of the node applications will fail to connect to the primary database, with selection timeout.

Steps I have taken includes restarting docker service on my ubuntu servers, deleting the stack and re-deploying the stack.

Sometimes it works (the node can connect back to the primary database), sometimes it doesn’t.

Inside the container that is having problem connecting, I have no problem pinging the database server, but I cannot connect via mongo client.

This question is very general, and it’s so random but happens all the time, so I hope someone can point me to some directions, to handling server restart/crashes.