MongoDB – Run Server as Service and mongod Instance on Ubuntu

mongodbUbuntu

I am using ubuntu and can run mongodb server by the following command

systemctl start mongodb

But, if i want to run Mongodb by mongod

mongod --dbpath /var/lib/mongodb

it gives me Permission Denied error.
Adding sudo before the mongod command fix the error and the Server starts.
But now, earlier command

systemctl start mongodb

won't work and says too many files open

So, I change the owner of the folder /var/log/mongodb and /var/lib/mongodb by the following commands.

sudo chown -R  mongodb:mongodb /var/log/mongodb
sudo chown -R  mongodb:mongodb /var/lib/mongodb

Now, MongoDb server started by systemctl command but again mongod command gives me error.
So, Is there any way to run Mongodb Server by both ways i.e, by using systemctl and mongod command.

Thanks

Best Answer

The following command has solved my problem

sudo -u mongodb mongod --dbpath /var/lib/mongodb

The -u mongodb after sudo runs the mongod with mongodb user. So,I don't have to change owner of folder /var/lib/mongodb to mongodb.

Now, I am able to start Mongodb Server as Service and also by mongod.