在 Ubuntu 上配置 MongoDB 开机自启动,主要取决于你使用的 Ubuntu 版本 和 MongoDB 的安装方式。下面分情况说明。
如果你是通过 MongoDB 官方源安装的(如 mongodb-org),MongoDB 会自带 systemd 服务。
systemctl status mongod
sudo systemctl start mongod
sudo systemctl enable mongod
systemctl is-enabled mongod
输出应为:
enabled
如果你用的是老版本 Ubuntu(14.04 及以前):
sudo service mongod start
sudo update-rc.d mongod defaults
如果你是 下载 tar 包自己解压 的 MongoDB,需要手动创建 systemd 服务。
sudo nano /etc/systemd/system/mongod.service
内容示例(根据实际路径修改):
[Unit]
Description=MongoDB Database Server
After=network.target
[Service]
ExecStart=/usr/local/mongodb/bin/mongod --config /etc/mongod.conf
User=mongodb
Group=mongodb
Restart=always
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl start mongod
sudo systemctl enable mongod
查看日志:
journalctl -u mongod
默认配置文件位置:
/etc/mongod.conf
数据目录(默认 /var/lib/mongodb)需属于 mongodb 用户:
sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo systemctl start mongod
sudo systemctl enable mongod
如果你是 Ubuntu 版本不确定 或 MongoDB 启动报错,可以把 systemctl status mongod 的输出发给我,我可以帮你具体分析。