You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot连接MongoDB时出现“Connection Refused”错误

Fixing MongoSocketOpenException in Spring Boot + MongoDB Project

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 with sudo 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 list to check status, or start it with brew 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.bindIp line—make sure it includes 127.0.0.1 (for localhost access) or is set to 0.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:46:47