Ubuntu 16.04系统中MongoDB连接被拒绝问题求助
Hey there, let's work through fixing this MongoDB connection issue on your Ubuntu 16.04 system step by step. First, let's recap the error you're encountering:
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
2018-03-27T18:23:41.006+0530 W NETWORK [thread1] 无法连接到127.0.0.1:27017,轮询后检查套接字错误,原因:Connection refused
2018-03-27T18:23:41.006+0530 E QUERY [thread1] 错误:无法连接到服务器127.0.0.1:27017,连接尝试失败 :
connect@src/mongo/shell/mongo.js:251:13
@(connect):1:6
exception: connect failed
Step 1: Check if the MongoDB service is running
The most common culprit here is that the mongod service isn't active. Run this command to check its status:
sudo systemctl status mongod
If the output shows "inactive (dead)" or similar, start the service immediately:
sudo systemctl start mongod
To avoid this issue on future system reboots, set the service to start automatically:
sudo systemctl enable mongod
Step 2: Verify port 27017 isn't occupied by another process
Sometimes another program might be using MongoDB's default port. Check with this command:
sudo netstat -tulpn | grep 27017
If netstat isn't installed on your system, use ss instead:
sudo ss -tulpn | grep 27017
If you see a different process listed here, you can either stop that process or modify MongoDB's port in its config file (covered next).
Step 3: Validate MongoDB's configuration file
Open the mongod config file with a text editor (nano is beginner-friendly):
sudo nano /etc/mongod.conf
Look for these critical settings:
bindIp: Ensure this is set to127.0.0.1(for local connections) or0.0.0.0(if you need remote access—only do this if you've secured your setup properly).port: Confirm it's set to27017(the default).
After making any changes, save the file (Ctrl+O then Enter in nano) and restart the service:
sudo systemctl restart mongod
Step 4: Check UFW firewall settings
Ubuntu 16.04 uses UFW by default, and it might be blocking port 27017. Allow the port with:
sudo ufw allow 27017
Reload the firewall to apply the change:
sudo ufw reload
Step 5: Dig into MongoDB logs for deeper issues
If none of the above fixes work, the logs will reveal more details. Check the last 20 lines of the mongod log:
sudo tail -n 20 /var/log/mongodb/mongod.log
A frequent issue here is incorrect permissions on the MongoDB data directory. If you see permission errors, fix them with:
sudo chown -R mongodb:mongodb /var/lib/mongodb sudo systemctl restart mongod
After trying these steps, run the mongo command again to test the connection. If you still run into problems, let me know what the logs or status commands show!
内容的提问来源于stack exchange,提问作者kaushal agrawal

