How to restart MongoDB automatically whenever the server / system reboots?

Ensuring MongoDB restarts automatically after a system reboot guarantees continuous availability of your database service. Below are the steps to configure this for various Linux distributions:

Ubuntu / Debian / CentOS / RedHat

1. Install MongoDB (if not already installed)

Refer to the official MongoDB documentation for detailed installation instructions for supported Linux distributions:

Install MongoDB on Linux

2. Edit the mongod.service file

MongoDB installation via official MongoDB packages usually includes a pre-configured systemd service unit file. You may find this file in either /lib/systemd/system/ or /etc/systemd/system/ directory. To locate the exact path, use:

Bash
systemctl status mongod.service

2.1. Open the mongod.service file

Depending on the location from the previous step, open the mongod.service file using a text editor:

Bash
sudo nano /lib/systemd/system/mongod.service

or

Bash
sudo nano /etc/systemd/system/mongod.service

2.2. Add Restart Directive

Within the [Service] section, add or modify the Restart directive to ensure MongoDB automatically restarts if it stops:

This setting tells systemd to restart the MongoDB service whenever it stops, whether due to an error, system reboot, or any other reason.

3. Reload systemd and Enable MongoDB Service

After modifying the mongod.service file, you need to reload the systemd configuration and enable the MongoDB service to start on boot:

Bash
sudo systemctl daemon-reload
sudo systemctl enable mongod.service
  • daemon-reload: Reloads the systemd manager configuration.
  • enable mongod.service: Enables the MongoDB service to start at boot.

Verification

To ensure MongoDB is set to start automatically on boot, check the status of the MongoDB service:

Bash
sudo systemctl status mongod.service

If configured correctly, you should see active (running) in the status output. If MongoDB is not running, you can start it manually using:

Bash
sudo systemctl start mongod.service

Additional Information

  • MongoDB Configuration: MongoDB’s configuration file is typically located at /etc/mongod.conf. Adjust this file to configure MongoDB settings like data directory, log path, etc.
  • Security: Always secure your MongoDB installation by setting up authentication, firewall rules, and regular backups. MongoDB provides built-in authentication and role-based access control.
  • Monitoring: Consider using monitoring tools like mongostat, mongotop, or third-party solutions to monitor MongoDB performance and health

By following these steps and best practices, you ensure that MongoDB is resilient to system reboots, providing uninterrupted service for your applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart