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

Ubuntu20.04重启后/var/run/mongodb/目录丢失致MongoDB无法启动

Ubuntu 20.04: MongoDB无法启动,重启后/var/run/mongodb目录丢失

问题详情

  • Ubuntu 20.04环境下,每次系统重启后/var/run/mongodb/目录被清空,导致MongoDB启动失败,报错「ERROR: Cannot write pid file to /var/run/mongodb/mongod.pid: No such file or directory」
  • 手动创建该目录后问题暂时解决,但重启后目录再次消失,问题重复出现
  • 当前使用的mongod.conf配置如下:
# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  wiredTiger:

# how the process runs
processManagement:
  fork: true  # fork and run in background
  pidFilePath: /var/run/mongodb/mongod.pid  # location of pidfile
  timeZoneInfo: /usr/share/zoneinfo

# network interfaces
net:
  port: 38512
  bindIp: 0.0.0.0  # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.


security:
  authorization: enabled
  keyFile: /var/lib/mongodb/replica_set_key

#operationProfiling:

replication:
  replSetName: "dbr"

#sharding:

## Enterprise-Only Options

#auditLog:

#snmp:

根治方案

/var/run属于tmpfs临时文件系统,系统重启后会自动清空所有内容,手动创建目录只是临时修复。要彻底解决,需要通过systemd服务配置让系统自动创建该目录:

  1. 编辑MongoDB的systemd服务文件:
sudo nano /lib/systemd/system/mongod.service
  1. 在[Service]段中添加以下两行配置:
RuntimeDirectory=mongodb
RuntimeDirectoryMode=0755

这会让systemd在启动MongoDB服务时,自动在/var/run下创建mongodb目录,并设置正确的权限(所有者为mongodb用户,权限755),完全适配tmpfs的特性。

  1. 重新加载systemd配置并重启服务:
sudo systemctl daemon-reload
sudo systemctl restart mongod
  1. 验证效果:重启系统后,检查目录是否自动生成,同时确认MongoDB状态正常:
ls -ld /var/run/mongodb
sudo systemctl status mongod

额外说明

  • 如果你是通过MongoDB官方deb包安装的,默认的systemd服务文件应该已经包含上述配置,可能是之前修改服务文件时误删了相关内容;如果是手动编译安装的MongoDB,则需要手动添加这些配置。
  • 确保服务文件中已经设置了User=mongodb(默认配置会有),配合RuntimeDirectoryMode=0755可以保证mongodb用户对目录有读写权限,避免pid文件写入失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 18:46:00