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:
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:
systemctl status mongod.service2.1. Open the mongod.service file
Depending on the location from the previous step, open the mongod.service file using a text editor:
sudo nano /lib/systemd/system/mongod.serviceor
sudo nano /etc/systemd/system/mongod.service2.2. Add Restart Directive
Within the [Service] section, add or modify the Restart directive to ensure MongoDB automatically restarts if it stops:
Restart=alwaysThis 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:
sudo systemctl daemon-reload
sudo systemctl enable mongod.servicedaemon-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:
sudo systemctl status mongod.serviceIf configured correctly, you should see active (running) in the status output. If MongoDB is not running, you can start it manually using:
sudo systemctl start mongod.serviceAdditional 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.
