15

I can't figure out how to auto-restart mongodb on Ubuntu 16.04 in the event that it crashes due to memory-pressure.

I'm using supervisord for other scripts etc, but mongod is through systemctl and I'm not sure how that ties into it.

Dev Sanghani
  • 1,145
  • 11
  • 19

2 Answers2

34

Figured it out:

  1. Edit your mongod service: sudo vim /lib/systemd/system/mongod.service
  2. Add Restart=always under service
  3. Reload systemctl daemon: sudo systemctl daemon-reload

Now whenever mongod gets killed. It'll get respawned by systemctl.

Dev Sanghani
  • 1,145
  • 11
  • 19
  • But how can you persist this when apt updates the service file when mongo updates> – Climax Jan 31 '19 at 08:32
  • if you are in aws then you can download it from s3 or somewhere. – Lovey Apr 03 '19 at 23:57
  • 3
    Instead of adding it to the file `/lib/systemd/system/mongod.service`, create a new file (and folder structure, if needed) at `/etc/systemd/system/mongod.service.d/always_restart.conf`. Then add the line `[Service]`, and after it add the one mentioned in the answer i.e `Restart=always`. Run step 3. and it will persists even when apt updates the service file. – Ashish Apr 22 '21 at 06:15
3

When you install mongoDB just run systemctl enable mongod.service on terminal.

This will make your mongoDB service auto-start on every restart.

Muhammad Usman
  • 10,039
  • 22
  • 39
  • 5
    Does this also work if mongodb just crashes? I thought systemctl enable only works for running the service on reboot - not when the service just crashes for whatever reason? – Dev Sanghani Apr 11 '18 at 07:14
  • @DevSanghani No this doesn't work, you are correct. `enable` only makes systemd start the service on boot. This answer is invalid. –  May 06 '20 at 02:52