You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux重启后自定义MongoDB实例终止,如何配置systemctl实现开机自启?

MongoDB自定义实例启动问题与systemctl配置方案

1. 当前启动方式存在的问题

你当前的启动方式仅适用于临时测试场景,核心问题如下:

  • 用&后台挂载的进程属于当前终端会话的子进程,会话断开、系统重启都会直接终止进程,无任何守护、自动恢复机制
  • 你将数据、日志、配置文件都放在了/tmp目录下,该目录为Linux系统临时目录,系统重启后会自动清空所有内容,你的MongoDB数据、配置重启后会完全丢失
  • 无进程监控能力,进程意外崩溃后无法自动拉起

2. 前置路径调整(必须操作)

首先需要将MongoDB相关目录迁移到非临时存储路径,避免数据丢失:

# 终止当前运行的MongoDB进程
ps aux | grep mongod | grep 27011 | awk '{print $2}' | xargs kill -9
# 迁移目录到/opt路径下
sudo mv /tmp/mongodb /opt/
# 修正配置文件中的路径,同时将端口配置写入配置文件
sudo sed -i 's|/tmp/mongodb|/opt/mongodb|g' /opt/mongodb/data1/db/mongod.cfg
sudo tee -a /opt/mongodb/data1/db/mongod.cfg << EOF
net:
    port: 27011
    bindIp: 127.0.0.1
processManagement:
    fork: false
EOF
# 创建专用运行用户,避免使用root运行MongoDB降低安全风险
sudo useradd -r -s /sbin/nologin mongod
sudo chown -R mongod:mongod /opt/mongodb

3. 配置systemctl服务实现开机自启

创建systemd服务配置文件:sudo vim /etc/systemd/system/mongod-custom.service,写入如下内容:

[Unit]
Description=MongoDB Custom Instance
After=network.target

[Service]
User=mongod
Group=mongod
ExecStart=/usr/bin/mongod --config /opt/mongodb/data1/db/mongod.cfg
Restart=on-failure
RestartSec=5
LimitNOFILE=64000
LimitNPROC=64000

[Install]
WantedBy=multi-user.target

执行后续生效操作:

  • 重载systemd配置:sudo systemctl daemon-reload
  • 启动自定义MongoDB实例:sudo systemctl start mongod-custom
  • 验证运行状态:sudo systemctl status mongod-custom,输出显示active (running)即为正常运行
  • 设置开机自启:sudo systemctl enable mongod-custom

4. 后续常用管理命令

  • 停止实例:sudo systemctl stop mongod-custom
  • 重启实例:sudo systemctl restart mongod-custom
  • 查看实时运行日志:journalctl -u mongod-custom -f

内容的提问来源于stack exchange,提问作者liran pana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 20:36:03