Install and Secure MongoDB on Ubuntu 22.04
- Make sure your system is up-to-date by running the following command:
sudo apt update
sudo apt upgrade
sudo apt install gnupg2
Step 1: Installing MongoDB
- Import the MongoDB GPG key
wget -nc https://www.mongodb.org/static/pgp/server-6.0.asc
cat server-6.0.asc | gpg --dearmor | sudo tee /etc/apt/keyrings/mongodb.gpg >/dev/null
- Add the MongoDB repository to your system’s package manager:
sudo sh -c 'echo "deb [ arch=amd64,arm64 signed-by=/etc/apt/keyrings/mongodb.gpg] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/6.0 multiverse" >> /etc/apt/sources.list.d/mongo.list'
- Update the list of available packages:
sudo apt install mongodb-org
- Start the MongoDB service:
sudo systemctl start mongod
Step 2: Securing MongoDB with a Password
- Connect to the MongoDB shell:
- Switch to the admin database:
- Create a privileged user account:
db.createUser({
user: "admin",
pwd: "<password>",
roles: [ { role: "root", db: "admin" } ]
})
Step 3: Enabling Authentication
- Edit the MongoDB configuration file:
- Find the security section in the configuration file and add the following lines:
security:
authorization: enabled
- Save the changes and exit the text editor.
- Restart the MongoDB service:
sudo systemctl restart mongod
- Connect to MongoDB with username/password:
mongosh -u admin -p'<password>'
Verify FireWall is not running:
- Check the status of the firewall: