How to secure MongoDB with username and password
- start mongo shell by typing
mongo
in terminal. - use admin database:
use admin
- create a new user and assign your intended role:
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: passwordPrompt(), // or cleartext password
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)
- exit mongo and add the following line to
etc/mongod.conf
:
security:
authorization: enabled
- restart mongodb server
(optional) 6.If you want your user to have root access you can either specify it when creating your user like:
db.createUser(
{
user: "myUserAdmin",
pwd: passwordPrompt(), // or cleartext password
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)
or you can change user role using:
db.auth("myUserAdmin", "abc123")
db.grantRolesToUser('myUserAdmin', [{ role: 'root', db: 'admin' }])
——————————————
MongoDB loads but breaks, returning status=14
Solution 1 :
fter googling around for a while. I found that that is because the permission settings on /var/lib/mongodb
and /tmp/mongodb-27017.lock
are wrong. You will have to change the owner to monogdb user
sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo chown mongodb:mongodb /tmp/mongodb-27017.sock
then
sudo systemctl restart mongod
sudo systemctl start mongod
sudo systemctl status mongod
sudo systemctl enable mongod
Solution 2:
deleting the mongod sock file solved the issue for me sudo rm -rf /tmp/mongodb-27017.sock
then start again sudo systemctl start mongod
or
By using this my error was gone:
- Go to the
TMP
directory:cd /tmp
- Check if you have the mongodb sock file:
ls *.sock
- Change the user:group permission:
chown mongodb:mongodb
- Start MongoDB:
sudo systemctl start mongod
- Check the MongoDB status:
sudo systemctl status mongod