SpringBoot应用无法连接Docker中运行的Mongo容器求助
Hey there, let's walk through how to fix this connection issue step by step—this is a common gotcha when working with Docker and Spring Boot, so we'll cover all the usual suspects:
1. Verify Docker Container Port Mapping & Status
First, make sure your MongoDB container is actually exposing the port correctly and running:
- Run
docker psto check if the mongo container is in theUpstate. Note the container ID/name. - Test if the local port 27017 is reachable from your host machine:
If this fails, your port mapping isn't working. Double-check your run command—you used# Using telnet telnet localhost 27017 # Or nc (netcat) if telnet isn't installed nc -zv localhost 27017-p 27017:27017, which is correct, but maybe the container failed to start properly. Check logs withdocker logs <your-container-id>, look for lines likewaiting for connections on port 27017to confirm MongoDB is ready.
2. Check Spring Boot Connection Configuration
Next, confirm your app's MongoDB connection settings are pointing to the right place:
- Open your
application.propertiesorapplication.ymlfile. The default connection string should look like:
Or for YAML:spring.data.mongodb.uri=mongodb://localhost:27017/test
Make sure there are no typos in the host (spring: data: mongodb: uri: mongodb://localhost:27017/testlocalhost) or port (27017). If you're using Docker Desktop on Windows/macOS and have issues withlocalhost, try replacing it withhost.docker.internal—this special DNS name points to your host machine from inside the Docker network.
3. Rule Out Firewall/Network Restrictions
Sometimes local firewalls or security tools block incoming connections to port 27017:
- Temporarily disable your host firewall (or add an exception for port 27017) and test the connection again.
- If you're on a corporate network, check if there are any network policies blocking the port.
4. Check Dependency Compatibility
Ensure your Spring Boot MongoDB starter version is compatible with the MongoDB version running in the container:
- Check your
pom.xml(orbuild.gradle) for thespring-boot-starter-data-mongodbdependency. For example, if you're running MongoDB 6.0+, you'll want Spring Boot 2.7.x or newer. Mismatched versions can cause connection handshake failures.
5. Test Alternative Network Mode (Debugging Only)
As a last debugging step, try running the MongoDB container in host network mode to bypass port mapping:
docker run --network host -d mongo
Then restart your Spring Boot app—if this works, it confirms the issue was with the bridge network port mapping. You can revert back to bridge mode once you've fixed the original problem.
内容的提问来源于stack exchange,提问作者Chethan B

