Docker中SpringBoot容器无法连接MongoDB问题求助
Hey there, let's troubleshoot why your Spring Boot app inside Docker can't reach your MongoDB container—especially since you can connect from outside Docker just fine! Here are the most common fixes to try:
1. Fix the MongoDB Connection String Syntax
First off, I spotted a typo in your code that's likely causing immediate issues:
// Your current code (missing colon in the protocol) MongoClient mongo = new MongoClient("mongodb//db", 27017));
The correct connection string format requires a colon after mongodb:
// Corrected code MongoClient mongo = new MongoClient("mongodb://db", 27017);
That tiny missing colon breaks the URL parsing, so fixing this is the first step.
2. Ensure Both Containers Are on the Same Docker Network
Docker containers can't communicate with each other using container names (like db) unless they're on the same network. By default, containers run in the generic bridge network, but creating a custom network is more reliable:
- Create a dedicated network for your services:
docker network create app-network - Run your MongoDB container attached to this network:
docker run -d --name db --network app-network mongo - Launch your Spring Boot container in the same network:
docker run -d --name spring-app --network app-network your-spring-boot-image
Now your Spring Boot app can resolve the db hostname to the MongoDB container's internal IP address.
3. Verify Connectivity Between Containers
If the above steps don't work, test direct connectivity from the Spring Boot container to MongoDB:
- Exec into the Spring Boot container to run diagnostic commands:
# Ping the MongoDB container to check DNS resolution docker exec -it spring-app ping db # Test if port 27017 is open docker exec -it spring-app telnet db 27017
If these commands fail, double-check that both containers are on the same network and the MongoDB container name is spelled correctly.
4. Check for MongoDB Authentication (If Enabled)
If you set up username/password authentication for MongoDB, make sure your connection string includes those credentials:
// With credentials MongoClient mongo = MongoClients.create("mongodb://admin:password@db:27017");
Or if you're using Spring's application properties:
spring.data.mongodb.uri=mongodb://admin:password@db:27017/your-database-name
Bonus: Use Docker Compose for Simplified Setup
For a smoother, more reproducible workflow, use Docker Compose. It automatically creates a shared network and manages service dependencies. Here's a basic example docker-compose.yml:
version: '3.8' services: db: image: mongo ports: - "27017:27017" spring-app: build: . depends_on: - db ports: - "8080:8080"
Run everything with docker-compose up, and your Spring Boot app can connect using db as the hostname without extra network configuration.
内容的提问来源于stack exchange,提问作者Priyanka Kanse

