首先确保系统软件包为最新状态,避免已知漏洞:
sudo apt-get update && sudo apt-get upgrade -y
添加MongoDB官方APT仓库(以MongoDB 6.0为例):
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu $(lsb_release -sc)/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list
sudo apt-get update
安装MongoDB:
sudo apt-get install -y mongodb-org
编辑MongoDB主配置文件/etc/mongod.conf,修改以下关键设置:
bindIp设置为127.0.0.1(仅本地访问)或添加特定IP(如127.0.0.1,192.168.1.100);security section添加authorization: enabled。net:
port: 27017
bindIp: 127.0.0.1 # 仅允许本地连接,生产环境可添加信任IP
security:
authorization: enabled # 启用用户认证
保存后重启MongoDB服务使配置生效:
sudo systemctl restart mongod
sudo systemctl enable mongod # 设置开机自启
使用MongoDB shell连接到本地实例,切换至admin数据库(系统级权限数据库),创建具有root角色(最高权限)的管理员用户:
mongo
use admin
db.createUser({
user: "admin",
pwd: "YourStrongPassword123!", # 使用强密码(包含大小写字母、数字、符号)
roles: [{ role: "root", db: "admin" }] # root角色拥有所有数据库管理权限
})
exit # 退出shell
为具体数据库创建专用用户,仅授予必要权限(如readWrite或readOnly)。例如,为mydb数据库创建mydbuser用户:
mongo -u admin -p YourStrongPassword123 --authenticationDatabase admin # 以管理员身份登录
use mydb
db.createUser({
user: "mydbuser",
pwd: "MyDbUserPassword456!",
roles: [{ role: "readWrite", db: "mydb" }] # 仅允许读写mydb数据库
})
exit
使用ufw(Ubuntu防火墙)限制MongoDB端口(默认27017)的访问,仅允许信任IP访问:
sudo ufw allow from 192.168.1.100 to any port 27017 # 替换为你的信任IP
sudo ufw enable # 启用防火墙
sudo ufw status # 验证规则(应显示允许的IP和端口)
为MongoDB配置SSL/TLS,加密客户端与服务器之间的通信(需提前获取SSL证书,如自签名或CA签发):
编辑/etc/mongod.conf,在net section添加:
net:
tls:
mode: requireTLS # 强制使用TLS
certificateKeyFile: /path/to/your/certificate.pem # 证书文件路径
CAFile: /path/to/your/ca.pem # CA证书路径(可选,用于验证客户端证书)
重启MongoDB服务:
sudo systemctl restart mongod
sudo apt-get update && sudo apt-get upgrade mongodb-org -y
/var/log/mongodb/mongod.log),关注异常登录或操作;通过以上步骤,可显著提升Ubuntu环境下MongoDB的安全性,防范未授权访问、数据泄露等风险。生产环境中还需根据实际需求调整权限粒度(如自定义角色)和加密策略。