Ubuntu MongoDB網絡設置指南
首先確保Ubuntu系統已安裝MongoDB,可通過以下命令快速安裝:
sudo apt update
sudo apt install -y mongodb
MongoDB的網絡配置集中在/etc/mongod.conf文件中,核心參數為net.bindIp(綁定IP地址)和net.port(監聽端口)。
sudo nano /etc/mongod.conf
bindIp:
0.0.0.0;192.168.1.100)或本地連接,設置為對應IP(多個IP用逗號分隔):net:
bindIp: 192.168.1.100,127.0.0.1 # 允許特定IP和本地回環
port: 27017 # 默認端口,可按需修改
Ctrl+X→Y→Enter確認。sudo systemctl restart mongod
可通過sudo systemctl status mongod驗證服務狀態(顯示active (running)即為正常)。
若系統啟用ufw防火墻,需放行MongoDB默認端口27017:
sudo ufw allow 27017
sudo ufw allow from 192.168.1.50 to any port 27017
sudo ufw status numbered
默認情況下,MongoDB未啟用認證,需通過配置文件開啟并創建管理員用戶:
/etc/mongod.conf的security部分添加:security:
authorization: enabled
sudo systemctl restart mongod
admin數據庫并創建用戶(示例密碼為YourStrongPassword,請替換為復雜密碼):mongo
use admin
db.createUser({
user: "admin",
pwd: "YourStrongPassword",
roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})
exit
從另一臺機器使用mongo命令測試連接(替換SERVER_IP為MongoDB服務器IP):
mongo -h SERVER_IP -u admin -p YourStrongPassword --authenticationDatabase admin
若成功進入MongoDB shell,說明網絡設置生效。
bindIp: 0.0.0.0,應僅允許信任的IP地址訪問。authorization并使用強密碼,避免未授權訪問。/var/log/mongodb/mongod.log)監控連接行為,及時發現異常。