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

Kill进程及重启EC2实例后MongoDB数据库消失,求排查方案

Troubleshooting Missing MongoDB Data After EC2 Restart

Hey there, this is a super common gotcha when manually starting MongoDB after an instance restart—let's figure out what's going on and get your data back.

What's Likely Happening

The core issue here is almost certainly that you're starting MongoDB with the wrong data directory path when you run sudo mongod --dbpath ./db. Here's why:

  • By default, MongoDB on most EC2 setups uses a system-level directory like /var/lib/mongodb (not a relative ./db folder in your current shell directory).
  • When you restart your EC2 instance, your default SSH working directory might change, so ./db points to a brand-new empty folder instead of the one that held your actual data.

Step-by-Step Fix

Let's walk through getting your data back:

  1. Stop the current empty mongod instance first
    Run this command to shut down the process using the same dbpath you started with:

    sudo mongod --dbpath ./db --shutdown
    

    If that fails, find the process ID and kill it:

    ps aux | grep mongod
    sudo kill <your-mongod-pid>
    
  2. Locate your actual MongoDB data directory
    There are two reliable ways to find this:

    • Check the MongoDB config file: Most systems store this at /etc/mongod.conf. Look for the dbPath field under the storage section:
      cat /etc/mongod.conf | grep -A 2 "storage"
      
      You should see something like:
      storage:
        dbPath: /var/lib/mongodb
      
    • Check MongoDB logs: If the config file isn't helpful, look for the dbpath in the system logs:
      sudo cat /var/log/mongodb/mongod.log | grep "dbpath"
      
      The log will have a line like dbpath=/var/lib/mongodb from previous successful starts.
  3. Start MongoDB with the correct data path
    Use the path you found to start the daemon:

    sudo mongod --dbpath /var/lib/mongodb
    

    Pro tip: For future restarts, use the system service instead of manual commands—it'll automatically use the config file's settings:

    sudo systemctl start mongod
    
  4. Verify your data is back
    Open the MongoDB shell and run show dbs—your filled databases should be visible again!

Prevent This From Happening Again

  • Avoid manual mongod starts: Use sudo systemctl start/stop/restart mongod instead. This ensures you're always using the configured data directory.
  • Double-check relative paths: Never use ./db or other relative paths for critical data directories—always use absolute paths (like /var/lib/mongodb) if you have to start manually.
  • Confirm your config: Periodically check /etc/mongod.conf to make sure the dbPath is set to the directory where your data lives.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:15:30