以下是在Ubuntu上配置MongoDB網絡的步驟及安全建議:
安裝MongoDB
sudo apt update
sudo apt install -y mongodb
修改配置文件(關鍵步驟)
編輯 /etc/mongod.conf,找到 net 部分:
bindIp: 0.0.0.0(生產環境不推薦)bindIp: 192.168.1.100,127.0.0.1(替換為實際IP)port: 27017(默認端口,可自定義)重啟MongoDB服務
sudo systemctl restart mongod
配置防火墻(UFW)
sudo ufw allow 27017/tcp
sudo ufw reload
sudo ufw allow from <IP_ADDRESS> to any port 27017
啟用安全認證(生產環境必做)
mongod.conf 中添加:security:
authorization: enabled
mongo shell 創建管理員用戶:use admin
db.createUser({
user: "admin",
pwd: "強密碼",
roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})
測試遠程連接
從其他機器執行:
mongo -h <服務器IP> -u admin -p "密碼" --authenticationDatabase admin
安全風險提示:
bindIp: 0.0.0.0,優先限制為可信IP。參考來源: