在 Debian 上“守护(守护进程化 / 保活)”MongoDB,常见做法有几种,从官方推荐到轻量级保活都有。下面按推荐程度说明。
如果你是通过 官方 MongoDB 包 安装的(如 mongodb-org),它已经自带 systemd 服务。
sudo systemctl start mongod
sudo systemctl enable mongod
sudo systemctl status mongod
sudo systemctl stop mongod
sudo systemctl restart mongod
✅ 优点
Restart=on-failure)假设你手动下载了 MongoDB 二进制文件。
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
LimitNOFILE=64000
[Install]
WantedBy=multi-user.target
sudo useradd -r -s /bin/false mongodb
sudo mkdir -p /var/lib/mongodb
sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo systemctl daemon-reload
sudo systemctl start mongod
sudo systemctl enable mongod
如果你不想用 systemd:
sudo apt install supervisor
配置:
[program:mongod]
command=/usr/local/mongodb/bin/mongod --config /etc/mongod.conf
autostart=true
autorestart=true
user=mongodb
sudo supervisorctl update
仅适合临时测试:
nohup mongod --dbpath /data/db > mongod.log 2>&1 &
❌ 缺点:
security:
authorization: enabled
net:
bindIp: 127.0.0.1,10.0.0.5
sudo ufw allow from 10.0.0.0/24 to any port 27017
| 方式 | 推荐度 | 自动重启 | 开机启动 |
|---|---|---|---|
| systemd | ⭐⭐⭐⭐⭐ | ✅ | ✅ |
| supervisor | ⭐⭐⭐ | ✅ | ✅ |
| nohup | ⭐ | ❌ | ❌ |
如果你愿意,可以告诉我:
我可以给你一份完全匹配你环境的配置。