Hi

start mongod when linux server restart

Create a MongoDB systemd Service Unit File:


Use a text editor (e.g., nano, vim, or gedit) to create a systemd service unit file for MongoDB. This file should be placed in the /etc/systemd/system/ directory and should have a .service extension. You will need superuser (root) privileges to create this file.


Open a terminal and run:


bash

Copy code

sudo nano /etc/systemd/system/mongodb.service





In the file, define the service as follows:


ini

Copy code

[Unit]

Description=MongoDB Database Server

Documentation=https://docs.mongodb.org/manual

After=network.target


[Service]

ExecStart=/usr/bin/mongod --config /etc/mongod.conf

User=mongodb

Group=mongodb

Restart=always

SyslogIdentifier=mongod


[Install]

WantedBy=multi-user.target





Make sure to adjust the ExecStart line to match the path to your mongod binary and configuration file (/etc/mongod.conf by default). Also, verify that the User and Group match your MongoDB configuration.


Reload systemd and Enable the Service:


After creating the MongoDB service unit file, you need to reload systemd's configuration and enable the service to start at boot:


bash

Copy code

sudo systemctl daemon-reload

sudo systemctl enable mongodb.service

Start the MongoDB Service:


You can start the MongoDB service immediately:


bash

Copy code

sudo systemctl start mongodb.service





Verify the Service Status:


To check the status of the MongoDB service, use the following command:


bash

Copy code

sudo systemctl status mongodb.service

This command should show that MongoDB is active and running.


Reboot to Test:


To test whether MongoDB starts automatically when the server restarts, simply reboot your Linux server:


bash

Copy code

sudo reboot





After the reboot, MongoDB should start automatically.


Your MongoDB server will now start automatically whenever your Linux server reboots. Be sure to adjust the paths and configuration parameters in the systemd service unit file to match your specific MongoDB setup.



Previous
Next Post »