Darshan Hiranandani : Unable to Connect MongoDB from Dockerized Spring Boot App on EC2

Hello everyone,

I’m facing an issue where my Spring Boot application, running inside a Docker container, is unable to connect to a MongoDB instance deployed on an EC2 server. The same Spring Boot app can connect without issues to MongoDB hosted on MongoDB Atlas, but when connecting to the MongoDB instance on EC2, it fails to do so.

Here’s the setup:

  • MongoDB: 7.0 (Replication enabled)
  • Server: Linux EC2
  • MongoDB Configuration: 3-node, 1-instance
  • Spring Boot: Inside Docker
  • MongoDB URL:

bash

Copy code

mongodb://dbadmin:pwd@Public_IP:37011,Public_IP:37022,Public_IP:37033/testdb?replicaSet=ReplSet1&authSource=admin&connectTimeoutMS=300000

Error:

When I try to run the application, I get the following error:

sql

Copy code

Caused by: com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches com.mongodb.client.internal.MongoClientDelegate$1@519f7d59.
Client view of cluster state is {type=REPLICA_SET, servers=[{address=Public_IP:37033, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: Connect timed out}},
{address=Public_IP:37011, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: Connect timed out}},
{address=Public_IP:37022, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: Connect timed out}}]

Details:

  • The error indicates a socket timeout and connection issues when trying to connect to the MongoDB replica set.
  • The EC2 instance and the MongoDB are properly set up, as I can connect to them from other tools without issue.
  • The EC2 MongoDB instance is accessible via its Public IP and port.

Questions:

  1. Could this be related to network/firewall settings or EC2 security group misconfigurations?
  2. Could Docker’s network settings or the internal network be blocking the connection to the EC2 MongoDB instance?
  3. Is there a specific MongoDB configuration needed when running it inside Docker?
  4. Any suggestions on troubleshooting or fixing the connection timeout?

I’d appreciate any insights or recommendations on this!

Thanks in advance!
Regards
Darshan Hiranandani

1 Like