在Linux下配置MongoDB,可以按照以下步骤进行:
对于基于Debian的系统(如Ubuntu):
sudo apt update
sudo apt install -y mongodb
对于基于Red Hat的系统(如CentOS):
sudo yum install -y mongodb-org
下载MongoDB安装包:
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-<version>.tgz
解压安装包:
tar -zxvf mongodb-linux-x86_64-<version>.tgz
sudo mv mongodb-linux-x86_64-<version> /usr/local/mongodb
创建数据目录并设置权限:
sudo mkdir -p /data/db
sudo chown -R `whoami` /data/db
启动MongoDB服务:
/usr/local/mongodb/bin/mongod --dbpath /data/db
MongoDB的配置文件通常位于/etc/mongod.conf。你可以编辑这个文件来修改配置。
# MongoDB Configuration File
storage:
dbPath: /data/db
journal:
enabled: true
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
net:
port: 27017
bindIp: 127.0.0.1
使用以下命令启动和停止MongoDB服务:
sudo systemctl start mongod
sudo systemctl stop mongod
sudo systemctl enable mongod
连接到MongoDB并创建一个管理员用户:
mongo
use admin
db.createUser({
user: "admin",
pwd: "your_password",
roles: ["root"]
})
编辑/etc/mongod.conf文件,启用身份验证:
security:
authorization: enabled
然后重启MongoDB服务:
sudo systemctl restart mongod
使用mongo命令连接到MongoDB:
mongo -u admin -p your_password --authenticationDatabase admin
如果你启用了防火墙,确保开放MongoDB的默认端口27017:
sudo firewall-cmd --zone=public --add-port=27017/tcp --permanent
sudo firewall-cmd --reload
MongoDB提供了丰富的监控和日志功能。你可以查看日志文件/var/log/mongodb/mongod.log来获取更多信息。
通过以上步骤,你应该能够在Linux系统上成功安装和配置MongoDB。