Kill进程及重启EC2实例后MongoDB数据库消失,求排查方案
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./dbfolder in your current shell directory). - When you restart your EC2 instance, your default SSH working directory might change, so
./dbpoints 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:
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 --shutdownIf that fails, find the process ID and kill it:
ps aux | grep mongod sudo kill <your-mongod-pid>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 thedbPathfield under thestoragesection:
You should see something like:cat /etc/mongod.conf | grep -A 2 "storage"storage: dbPath: /var/lib/mongodb - Check MongoDB logs: If the config file isn't helpful, look for the dbpath in the system logs:
The log will have a line likesudo cat /var/log/mongodb/mongod.log | grep "dbpath"dbpath=/var/lib/mongodbfrom previous successful starts.
- Check the MongoDB config file: Most systems store this at
Start MongoDB with the correct data path
Use the path you found to start the daemon:sudo mongod --dbpath /var/lib/mongodbPro tip: For future restarts, use the system service instead of manual commands—it'll automatically use the config file's settings:
sudo systemctl start mongodVerify your data is back
Open the MongoDB shell and runshow dbs—your filled databases should be visible again!
Prevent This From Happening Again
- Avoid manual
mongodstarts: Usesudo systemctl start/stop/restart mongodinstead. This ensures you're always using the configured data directory. - Double-check relative paths: Never use
./dbor 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.confto make sure thedbPathis set to the directory where your data lives.
内容的提问来源于stack exchange,提问作者cuuupid

