下面给你一份在 Linux 上配置 MongoDB(以 Ubuntu / CentOS 为例)的实用指南,从安装 → 启动 → 基础配置 → 安全配置一步步来。
# 导入公钥
curl -fsSL https://pgp.mongodb.com/server-7.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
# 添加源
echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] \
https://repo.mongodb.org/apt/ubuntu $(lsb_release -cs)/mongodb-org/7.0 multiverse" | \
sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
# 安装
sudo apt update
sudo apt install -y mongodb-org
sudo tee /etc/yum.repos.d/mongodb-org-7.0.repo <<EOF
[mongodb-org-7.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/9/mongodb-org/7.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://pgp.mongodb.com/server-7.0.asc
EOF
sudo yum install -y mongodb-org
sudo systemctl start mongod
sudo systemctl enable mongod
sudo systemctl start mongod
sudo systemctl enable mongod
查看状态:
sudo systemctl status mongod
MongoDB 配置文件位置:
/etc/mongod.conf
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
net:
port: 27017
bindIp: 127.0.0.1 # 默认只允许本机
修改后重启:
sudo systemctl restart mongod
⚠️ 生产环境不建议直接暴露 27017
net:
bindIp: 0.0.0.0
然后开放防火墙:
sudo ufw allow 27017
mongosh
use admin
db.createUser({
user: "admin",
pwd: "StrongPassword",
roles: ["root"]
})
编辑 /etc/mongod.conf:
security:
authorization: enabled
重启:
sudo systemctl restart mongod
登录:
mongosh -u admin -p --authenticationDatabase admin
# 查看数据库
show dbs
# 使用数据库
use test
# 插入数据
db.users.insertOne({name:"tom"})
# 查看
db.users.find()
✅ 使用 副本集(Replica Set)
✅ 启用 TLS
✅ 使用 防火墙 + 内网
✅ 定期备份(mongodump)
如果你告诉我:
我可以给你一份更精准的配置方案。