You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Spring Boot连接MongoDB超时求助:已配置远程访问仍失败

Troubleshooting Spring Boot-MongoDB Remote Connection Timeout

Hey there, let's work through this issue together—remote MongoDB connections can trip up even experienced devs, so don't stress! Based on your setup and the timeout error you're seeing, here are the most likely fixes to check:

1. Verify MongoDB's bind_ip Configuration (and Restart the Service)

First, double-check your mongodb.conf to make sure the bind_ip is actually allowing external connections:

  • Open the config file (usually at /etc/mongod.conf) and look for the net section:
    net:
      port: 27017
      bindIp: 0.0.0.0  # This allows connections from ANY IP; use your host machine's IP if you want to restrict it
    
  • If you had it set to just 127.0.0.1 or the VM's local IP, that's why your Spring Boot app can't reach it. After updating, restart MongoDB to apply changes:
    sudo systemctl restart mongod
    

2. Check Ubuntu's Firewall (UFW)

This is the #1 culprit for timeout errors on Ubuntu VMs. By default, UFW blocks incoming traffic to most ports:

  • Check if UFW is active:
    sudo ufw status
    
  • If it shows active, you need to explicitly allow traffic on port 27017:
    sudo ufw allow 27017
    
  • For testing purposes, you can temporarily disable UFW to confirm it's the issue:
    sudo ufw disable
    
    If your Spring Boot app connects after this, re-enable UFW and keep the port 27017 rule in place.

3. Confirm Network Reachability Between Host and VM

Make sure your host machine can actually reach the Ubuntu VM:

  • Ping the VM's IP from your host:
    ping 192.x.x.x
    
    If ping fails, check your VM's network settings:
    • If using NAT mode in your hypervisor, you may need to set up port forwarding for 27017.
    • Switching to Bridge Mode often simplifies direct network access between host and VM.

4. Check for MongoDB Authentication Requirements

If you've enabled authentication on your MongoDB instance, your Spring Boot config is missing critical properties. Add these to your application.properties:

spring.data.mongodb.username=your-mongo-user
spring.data.mongodb.password=your-mongo-password
spring.data.mongodb.database=your-target-db

5. Test with a MongoDB Client First

Rule out Spring Boot as the issue by connecting directly to the VM's MongoDB using a client like MongoDB Compass or the mongo shell on your host:

mongo mongodb://192.x.x.x:27017

If this fails, the problem is definitely with MongoDB's network setup, not your Spring Boot app. If it works, double-check your Spring Boot dependencies (make sure you're using the correct spring-boot-starter-data-mongodb version) and config values.


内容的提问来源于stack exchange,提问作者Lakshmi

火山引擎 最新活动