在Linux上部署MongoDB的步骤如下:
对于基于Debian的系统(如Ubuntu):
sudo apt update
sudo apt install -y mongodb
对于基于Red Hat的系统(如CentOS):
sudo yum install -y mongodb-org
tar -zxvf mongodb-linux-x86_64-<version>.tgz
/usr/local/mongodb:sudo mv mongodb-linux-x86_64-<version> /usr/local/mongodb
echo 'export PATH=/usr/local/mongodb/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
sudo mkdir -p /data/db
创建一个配置文件 /etc/mongod.conf,并根据需要进行配置。以下是一个基本的配置示例:
storage:
  dbPath: /data/db
systemLog:
  destination: file
  logAppend: true
net:
  port: 27017
  bindIp: 127.0.0.1
sudo systemctl start mongod
/usr/local/mongodb/bin/mongod --config /etc/mongod.conf
sudo systemctl enable mongod
创建一个 systemd 服务文件 /etc/systemd/system/mongod.service:
[Unit]
Description=MongoDB Database Server
After=network.target
[Service]
ExecStart=/usr/local/mongodb/bin/mongod --config /etc/mongod.conf
Restart=always
[Install]
WantedBy=multi-user.target
然后启用并启动服务:
sudo systemctl daemon-reload
sudo systemctl enable mongod
sudo systemctl start mongod
使用 mongo 命令连接到MongoDB服务器:
mongo
如果你需要从远程机器访问MongoDB,确保防火墙允许端口27017的流量:
sudo ufw allow 27017
启用身份验证:
在 mongod.conf 中添加或修改以下配置:
security:
  authorization: enabled
然后重启MongoDB服务。
创建管理员用户:
mongo
use admin
db.createUser({
  user: "admin",
  pwd: "your_password",
  roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})
通过以上步骤,你应该能够在Linux系统上成功部署MongoDB。根据具体需求,你可能还需要进行更多的配置和优化。