在Ubuntu上配置MongoDB时,遵循以下最佳实践可以帮助确保其高效、安全地运行:
wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add - echo "deb [ archamd64,arm64 ] https://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-get update sudo apt-get install -y mongodb-org sudo nano /etc/mongod.conf bind_ip:设置为 0.0.0.0 以允许从任意IP地址连接。port:设置为 MongoDB 服务器监听的端口号(默认为27017)。security.authorization:启用身份验证(如果需要)。例如:
net: port: 27017 bindIp: 0.0.0.0 security: authorization: enabled sudo systemctl restart mongod sudo systemctl start mongod sudo systemctl stop mongod sudo systemctl restart mongod sudo systemctl status mongod mongo show dbs use mydb show collections 在配置文件中添加或修改以下内容:
security: authorization: enabled 切换到MongoDB shell:
mongo 切换到 admin 数据库:
use admin 创建一个管理员用户并授予其 root 角色:
db.createUser({ user: "yourAdminUsername", pwd: "yourAdminPassword", roles: [ { role: "root", db: "admin" } ] }) 退出MongoDB shell:
exit() mongostat 和 mongotop 监控数据库性能。sudo nano /etc/systemd/system/disable-thp.service 内容:
[Unit] Description = Disable Transparent Huge Pages (THP) [Service] Type = simple ExecStart = /bin/sh -c "echo 'never' /sys/kernel/mm/transparent_hugepage/enabled && echo 'never' /sys/kernel/mm/transparent_hugepage/defrag" [Install] WantedBy = multi-user.target 重新加载并启用服务:
sudo systemctl daemon-reloadsudo systemctl enable --now disable-thp.service sudo nano /etc/security/limits.d/mongodb.conf 内容:
mongod soft nproc 64000 mongod hard nproc 64000 mongod soft nofile 64000 mongod hard nofile 64000 mongosh use admin db.createUser({ user: "admin", pwd : "yourAdminPassword", roles: [ { role: "userAdminAnyDatabase" , db: "admin" } ] }) 通过以上步骤和最佳实践,您可以在Ubuntu上成功安装、配置、启动和验证MongoDB,并确保其高效和安全地运行。请根据您的实际需求调整配置,例如设置身份验证、指定数据存储路径等。