Containerized Spring boot App unable to connect to MongoDB

My Spring boot app is able to connect to Mongo DB and running fine as standalone app.
However, if the same app is set to run in Docker, the DB connection fails with exception ‘’

My Setup :
Spring boot App is running in docker, Mongo is outside of Docker.
Spring boot version : 2.7.4
Java Version : 11
Mongo DB version : v4.2.21 ( Running outside of Docker). Local and Stage environments have standalones installations with replicaSet.(PROD is more comprehensive)

mongodb URL from,localhost,

ClusterDescription when running as Standalone {type=REPLICA_SET, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=, type=REPLICA_SET_PRIMARY, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=8, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=13735215, setName=‘myreplicaset’, canonicalAddress=localhost:27017, hosts=[localhost:27017], passives=, arbiters=, primary=‘localhost:27017’, tagSet=TagSet{}, electionId=7fffffff0000000000000028, setVersion=1, topologyVersion=null, lastWriteDate=Tue Dec 13 16:29:48 EST 2022, lastUpdateTimeNanos=3150768696200}]}

ClusterDescription when running inside a Docker Container {type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by { Connection refused (Connection refused)}}]}

pom.xml entries

org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-data-mongodb

Can anyone tell me the reason for connection issues?

Thanks in advance,

Is mongodb running inside the container?
If not, perhaps does not refer to the outer host if used from within the container.

No. Mongo is not running inside the container.

Well, I could be wrong here, but I don’ t think localhost ( from within the container refers to the localhost hosting the container.

1 Like

You are not wrong.

1 Like

Thank you for the explanation. So, instead of ‘localhost’, should I be using hostname, IP address ?

Yes, and of course, you’ll need to configure mongod to be listening on the external interface as well as its

1 Like