Centos – MongoDB won’t run if dbPath is symlinked

centoscentos7mongodbselinuxsymbolic-link

I have installed MongoDB 4.0.4 from the official repo. I followed these instructions. My OS is CentOS 7 and SELinux is in enforcing mode. If I use a dbPath value which is a symlink to another directory, I get the following error in the log:

exception in initAndListen: Location28596: Unable to determine status of lock file in the data directory /var/lib/mongo_test: boost::filesystem::status: Permission denied: "/var/lib/mongo_test/mongod.lock", terminating

If I change the dbPath to any other directory which is not symlinked, it will work fine.

This is my current test setup and it will give an error:

# ln -s /var/lib/mongo /var/lib/mongo_test

# chcon -u system_u -t mongod_var_lib_t -h /var/lib/mongo_test

# cat /etc/mongod.conf | grep -v '^$\|^\s*\#'
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log
storage:
  dbPath: /var/lib/mongo_test
  journal:
    enabled: true
processManagement:
  fork: true
  pidFilePath: /var/run/mongodb/mongod.pid
  timeZoneInfo: /usr/share/zoneinfo
net:
  port: 27017
  bindIp: 127.0.0.1

# ls -alZ /var/lib/ | grep mongo
drwxr-xr-x. mongod    mongod    system_u:object_r:mongod_var_lib_t:s0 mongo
lrwxrwxrwx. root      root      system_u:object_r:mongod_var_lib_t:s0 mongo_test -> /var/lib/mongo

# namei -l /var/lib/mongo_test/mongod.lock
f: /var/lib/mongo_test/mongod.lock
dr-xr-xr-x root   root   /
drwxr-xr-x root   root   var
drwxr-xr-x root   root   lib
lrwxrwxrwx root   root   mongo_test -> /var/lib/mongo
dr-xr-xr-x root   root     /
drwxr-xr-x root   root     var
drwxr-xr-x root   root     lib
drwxr-xr-x mongod mongod   mongo
-rw------- mongod mongod mongod.lock

Best Answer

You're almost certainly running into SELinux here. While it expects and permits access to the data directory /var/lib/mongo, or more specifically files and directories having the SELinux type mongod_var_lib_t, it knows nothing of your symbolic link, as it probably doesn't have this type.

If you change the SELinux type of the symlink, you may find that MongoDB is able to acceess the database again.

chcon -h -t mongod_var_lib_t /var/lib/mongo_test

Note that you probably aren't done at this point. If you're messing with symlinks like this, you probably intend to do something like putting all your data on some other disk. In that case, you also need to make the contexts persistent (see here).