在 Ubuntu 上开启(启动并配置)MongoDB,通常分为 安装、配置、启动 几个步骤。下面以 Ubuntu 20.04 / 22.04 + MongoDB 6.x / 7.x 为例说明。
# 导入公钥
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
MongoDB 默认配置文件在:
/etc/mongod.conf
常见配置项示例:
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
net:
port: 27017
bindIp: 127.0.0.1
如需远程访问,将
bindIp改为:
bindIp: 0.0.0.0
# 启动
sudo systemctl start mongod
# 开机自启
sudo systemctl enable mongod
# 查看状态
sudo systemctl status mongod
mongo
use admin
db.createUser({
user: "admin",
pwd: "你的密码",
roles: [{ role: "root", db: "admin" }]
})
sudo nano /etc/mongod.conf
添加:
security:
authorization: enabled
sudo systemctl restart mongod
mongo -u admin -p --authenticationDatabase admin
sudo ufw allow 27017
查看日志:
sudo tail -n 50 /var/log/mongodb/mongod.log
sudo chown -R mongodb:mongodb /var/lib/mongodb
如果你是指 “开启某个 MongoDB 配置项(如副本集、慢查询、TLS)”,可以告诉我具体需求,我可以给你对应配置示例。