sudo apt update && sudo apt upgrade -y
wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-archive-keyring.gpg
focal代表22.04)选择对应URL,创建源文件。echo "deb [signed-by=/usr/share/keyrings/mongodb-archive-keyring.gpg] http://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list
sudo apt install -y mongodb-org
sudo systemctl start mongod
sudo systemctl enable mongod
sudo systemctl status mongod
# 若显示“active (running)”则表示成功
nano)打开MongoDB主配置文件。sudo nano /etc/mongod.conf
0.0.0.0)或仅本地访问(127.0.0.1)。net:
bindIp: 0.0.0.0 # 允许所有IP连接
port: 27017 # 默认端口,可修改(需同步防火墙)
/var/lib/mongodb)。storage:
dbPath: /var/lib/mongodb
journal: enabled # 启用日志,确保数据持久化
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
security:
authorization: enabled
sudo systemctl restart mongod
admin数据库创建具有root角色的用户(用于管理所有数据库)。mongo
use admin
db.createUser({
user: "adminUser",
pwd: "YourSecurePassword123!",
roles: [{ role: "root", db: "admin" }]
})
exit
mongo -u adminUser -p --authenticationDatabase admin
systemctl命令确保MongoDB随系统启动。sudo systemctl enable mongod
storage:
wiredTiger:
engineConfig:
cacheSizeGB: 2 # 示例:分配2GB内存给WiredTiger
use mydb
db.createUser({
user: "myUser",
pwd: "MySecurePassword456!",
roles: [{ role: "readWrite", db: "mydb" }]
})
sudo ufw allow 27017
mongodump备份数据,避免数据丢失。通过以上步骤,可在Ubuntu上完成MongoDB的安装、基础配置及安全设置,满足大多数应用场景的需求。