Spring Boot连接MongoDB时出现“Connection Refused”错误
Hey there, let's work through this MongoDB connection error you're hitting when running your Spring Boot JAR. That com.mongodb.MongoSocketOpenException message tells us your application can't establish a socket connection to MongoDB at localhost:27017—here are the most common fixes to get things working:
1. Make sure MongoDB service is running
First things first: is your MongoDB server actually up and running?
- On Linux, check with
systemctl status mongod; if it's inactive, start it withsudo systemctl start mongod - On Windows, open the Services app (search "Services" in the Start menu), find "MongoDB", and make sure its status is "Running". If not, right-click > Start
- On Mac, if you installed via Homebrew, run
brew services listto check status, or start it withbrew services start mongodb-community
2. Verify MongoDB port configuration
MongoDB uses 27017 by default, but if you've changed it in your MongoDB config, you need to update your Spring Boot settings to match:
- In
application.properties:spring.data.mongodb.port=your-custom-port - In
application.yml:spring: data: mongodb: port: your-custom-port
3. Check MongoDB's bind IP setting
Sometimes MongoDB is configured to only listen on specific IP addresses, which can block localhost connections.
- Open your MongoDB config file (Linux/Mac:
/etc/mongod.conf; Windows:<MongoDB-install-dir>/bin/mongod.cfg) - Look for the
net.bindIpline—make sure it includes127.0.0.1(for localhost access) or is set to0.0.0.0(allows all IPs, use carefully in production) - Save the config and restart the MongoDB service
4. Double-check Spring Boot's MongoDB connection config
Ensure your Spring Boot app is pointing to the right host/port/database:
Using properties file:
spring.data.mongodb.host=localhost spring.data.mongodb.port=27017 spring.data.mongodb.database=your-db-name
Using YAML file:
spring: data: mongodb: host: localhost port: 27017 database: your-db-name
Or using a connection URI:
spring.data.mongodb.uri=mongodb://localhost:27017/your-db-name
5. Rule out firewall/security software interference
Local firewalls or antivirus tools might be blocking traffic on port 27017. Try temporarily disabling them to see if the connection works, then add an exception for MongoDB's port if that fixes the issue.
If you've tried all these steps and still run into problems, feel free to share more details like your MongoDB config or Spring Boot application properties, and we can dig deeper!
内容的提问来源于stack exchange,提问作者Usman Khaliq

