wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list
sudo apt update
sudo apt install -y mongodb-org
sudo systemctl start mongod
sudo systemctl enable mongod.service
mongosh
Switch to admin db and create a new user with admin access to all databases.
use admin
db.createUser(
{
user: "myAdminUsername",
pwd: passwordPrompt(), // or cleartext password
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" }
]
}
)
Now exit out of mongo.
Below is the default /etc/mongod.conf file without any changes. This is here just for referance if we need to revert back any default configuration. No further things to do in this step.
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
# engine:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
# network interfaces
net:
port: 27017
bindIp: 127.0.0.1
# how the process runs
processManagement:
timeZoneInfo: /usr/share/zoneinfo
#security:
#operationProfiling:
#replication:
#sharding:
## Enterprise-Only Options:
#auditLog:
#snmp:
Open the mongod.conf file
sudo nano /etc/mongod.conf
Uncomment the security section and add the following
security:
authorization: enabled
This is totally otpional. The default port for mongodb is 27017. To set this to something else, make the following change.
net:
port: 12345
sudo systemctl restart mongod.service
After enabling authentication and changing to a custom port, try to connect using following command:
mongosh --port <custom port> <auth db name> -u <admin username> -p <admin password>
and once connected, make sure that the authentication worked by typingshow dbs
and it must list the default databses.
Example:
mongosh --port 12345 admin -u myUsername -p myPassword
- Allow access from any IP (less secure and not recommended)
net:
port: 27017 // or any other custom port
bindIp: 0.0.0.0
- Allow access from specific IP(s)
net:
port: 27017 // or any other custom port
bindIp: 127.0.0.1,192.168.0.10,192.168.0.12
sudo systemctl restart mongod.service
Make sure to allow the mongo port through firewall