MongoDB only works when run as root on Ubuntu - data directory issue

27,699

Solution 1

You created /data/db as root so it has those permissions. You can change the permissions to your user account, or whatever you have mongo running as.

chown -R username /data/db

or /data

You can also set a group

chown -R username.groupname

The -R does it recursively, so it will affect all the files you've created running mongoDB as root already.

Solution 2

I just had the same issue on RHEL 8, in year 2021.

I could run sudo mongod with sudo privileges but could not start it as a service with: sudo systemctl start mongod.

I tried many solutions and tested after each attempt, what ultimately solved it for me is changing ownership of /data/db/, /var/lib/mongo/, and /var/log/mongodb/ to mongod.

exact commands:

sudo chown -R mongod:mongod /var/lib/mongo/
sudo chown -R mongod:mongod /var/log/mongodb/
sudo chown -R mongod:mongod /data/
Share:
27,699
YXD
Author by

YXD

o.O

Updated on August 03, 2021

Comments

  • YXD
    YXD almost 3 years

    I installed MongoDB with the official packages (mongodb-stable), and followed the Quickstart guide which includes:

    By default MongoDB will store data in /data/db, but it won't automatically create that directory. To create it, do:

    $ sudo mkdir -p /data/db/
    $ sudo chown `id -u` /data/db
    

    You can also tell MongoDB to use a different data directory, with the --dbpath option.

    MongoDB will only start if I run sudo mongod - if I try and run just mongod I get the error:

    Mon Mar 14 15:27:07 [initandlisten] couldn't open /data/db/test.ns errno:13 Permission denied
    Mon Mar 14 15:27:07 [initandlisten]   couldn't open file /data/db/test.ns terminating
    Mon Mar 14 15:27:07 dbexit:
    

    What gives?

  • Emmanuel M. Smith
    Emmanuel M. Smith over 12 years
    Any benefit to leaving the owner as root and just assigning a group? Or is it better to specifically set the owner as a user?
  • Aaron
    Aaron almost 12 years
    Thanks, I was chowning the directory to mongodb:mongodb instead of my username:my group.
  • Mathias Haugsbø
    Mathias Haugsbø over 8 years
    Remember that you maybe have to run sudo infront of chown -R username /data/db