当您遇到无法连接到 MongoDB 27017 端口的问题时,可以按照以下步骤进行排查和解决:
Linux/Unix/MacOS:
sudo systemctl status mongod
# 或
sudo service mongod status
Windows:
net start | findstr "MongoDB"
如果服务未运行,启动服务:
sudo systemctl start mongod # Linux
# 或
net start MongoDB # Windows
查看日志文件以获取错误信息:
# 通常位置
tail -f /var/log/mongodb/mongod.log # Linux
# 或检查 Windows 服务日志
netstat -tulnp | grep 27017 # Linux
# 或
ss -tulnp | grep 27017
# Windows
netstat -ano | findstr 27017
如果没有监听,可能是配置问题或服务未正确启动。
默认配置文件位置:
- Linux: /etc/mongod.conf
- Windows: <install-path>\bin\mongod.cfg
确保 net.bindIp
配置正确:
net:
port: 27017
bindIp: 127.0.0.1 # 或 0.0.0.0 允许所有IP访问
修改后重启服务:
sudo systemctl restart mongod
Linux:
sudo ufw allow 27017 # Ubuntu
# 或
sudo firewall-cmd --add-port=27017/tcp --permanent # CentOS
sudo firewall-cmd --reload
Windows: - 控制面板 > Windows Defender 防火墙 > 高级设置 - 添加入站规则允许 27017 端口 TCP 连接
mongo --host 127.0.0.1 --port 27017
如果本地能连接但远程不能,检查 bindIp
配置和防火墙。
如果启用了认证:
mongo -u username -p password --authenticationDatabase admin
如果以上方法无效,可以尝试:
- 以调试模式启动 MongoDB
- 使用 strace
(Linux) 跟踪系统调用
- 检查 SELinux/AppArmor 是否阻止了访问
希望这些步骤能帮助您解决 MongoDB 连接问题!