在 Ubuntu 上让 MongoDB 开机自启,取决于你使用的 Ubuntu 版本 和 MongoDB 安装方式。下面分情况说明。
如果你是通过官方源安装的 MongoDB(如 mongodb-org),它默认使用 systemd。
systemctl list-unit-files | grep mongo
通常是:
mongod.service
sudo systemctl enable mongod
sudo systemctl start mongod
sudo systemctl status mongod
✅ 这样重启服务器后 MongoDB 会自动启动。
如果你安装的是:
sudo apt install mongodb
服务名可能是:
mongodb.service
操作方式相同:
sudo systemctl enable mongodb
sudo systemctl start mongodb
如果你是 手动解压 MongoDB,需要自己写 systemd 服务。
sudo nano /etc/systemd/system/mongod.service
示例内容:
[Unit]
Description=MongoDB Database Server
After=network.target
[Service]
User=mongodb
ExecStart=/usr/local/mongodb/bin/mongod --config /etc/mongod.conf
Restart=on-failure
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable mongod
sudo systemctl start mongod
如果是非常老的 Ubuntu:
echo "mongod hold" | sudo dpkg --set-selections
或通过:
sudo update-rc.d mongod defaults
journalctl -u mongod -xe
确保:
/var/lib/mongodb)属主正确如果你告诉我:
lsb_release -a)我可以给你更精确的配置。