Installing and Securing MongoDB® on Ubuntu
MongoDB is a document-oriented database, available for free as an open-source solution. Renowned for its scalability, robustness, reliability, and user-friendly nature, it is one of the premier choices among NoSQL database engines.
Diverging from traditional relational databases, MongoDB® users no longer need an intricate predefined schema before adding data. This flexibility stems from its ability to modify schemas at any point in time. Embracing the NoSQL philosophy, it employs JSON-like documents for data storage, allowing the insertion of diverse and arbitrary data.
Powerful General Purpose Instance comes with the compute and storage capabilities you need to run your MongoDB® Instance smoothly.
Before you start
To complete the actions presented below, you must have:
- A Scaleway account logged into the console
- Owner status or IAM permissions allowing you to perform actions in the intended Organization
- An SSH key
- An Instance running on Ubuntu Noble Numbat (24.04) or later
sudoprivileges or access to the root user
Setting up MongoDB
Adding MongoDB® repository
-
Connect to your Instance via SSH.
ssh root@your.instance.ip.addressIf you do not know your server IP, you can list your existing servers using the Scaleway CLI
scw instance server list. -
Update the Ubuntu package manager.
apt update -
Upgrade the Ubuntu packages already installed.
apt upgrade -
Import the key for the official MongoDB® repository (Ubuntu ensures the authenticity of software packages by verifying that they are signed with GPG keys.).
curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | \ sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg \ --dearmorThe command above should respond with an
OK. -
Add the MongoDB® repository details so that Ubuntu's
aptcommand-line tool will know where to download the packages. Execute the following command to create a list file for MongoDB.echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list -
Update the packages list:
apt update
Installing MongoDB
-
Install the
mongodb-orgmeta-package, which includes the daemon, configuration, and init scripts, shell, and management tools on the server.apt install mongodb-org -
Press enter or type
Yto proceed when prompted. Once the installation is completed, start the MongoDB® daemon.systemctl start mongod.service -
Verify that the service has started properly.
systemctl status mongod.serviceAn output similar to the following displays.
● mongod.service - MongoDB Database Server Loaded: loaded (/usr/lib/systemd/system/mongod.service; disabled; preset: > Active: active (running) since Mon 2024-09-16 09:36:51 UTC; 12s ago Docs: https://docs.mongodb.org/manual Main PID: 3664 (mongod) Memory: 72.9M (peak: 73.4M) CPU: 505ms CGroup: /system.slice/mongod.service └─3664 /usr/bin/mongod --config /etc/mongod.confType
qto exit. -
Ensure that it restarts automatically at each boot:
systemctl enable mongod.serviceCreated symlink from /etc/systemd/system/multi-user.target.wants/mongod.service to /lib/systemd/system/mongod.service.
Securing MongoDB
The default installation of MongoDB is vulnerable because no authentication is required to interact with the database. Any user can create and destroy databases, as well as read from and write to their contents by default. To secure MongoDB, you must create an administrative user and enable authentication.
-
Connect to the Mongo shell to add a new user.
mongoshConnecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.10.6 Using MongoDB: 7.0.0 Using Mongosh: 1.10.6 For mongosh info see: https://docs.mongodb.com/mongodb-shell/You can choose any preferred name for the administrative user since the privilege level is assigned from the role of
userAdminAnyDatabase.The
admindatabase designates where the credentials are stored. You can learn more about authentication in the MongoDB® Security Authentication section. -
Set the username of your choice and pick your own secure password, then substitute them in the command below:
use admin db.createUser( { user: "AdminOce", pwd: "PWD2018AdminOce", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } )The command above returns:
{ ok: 1 } -
Type
exitand press ENTER or useCTRL+Cto leave the client.admin> exit
Enabling authentication
To enforce authentication, you must enable authentication and restart the MongoDB daemon.
-
Open the configuration file.
nano /etc/mongod.conf -
Remove the hash in front of
securityto enable the section, then, addauthorization: "enabled"(indented with two spaces) on the following line as shown below:security: authorization: "enabled" -
Restart the daemon.
systemctl restart mongod.service -
Check the status to verify that the service has rebooted.
systemctl status mongod● mongod.service - MongoDB® Database Server Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor prese> Active: active (running) since Tue 2022-03-01 10:43:45 UTC; 2s ago Docs: https://docs.mongodb.org/manual Main PID: 21449 (mongod) Memory: 153.2M CGroup: /system.slice/mongod.service └─21449 /usr/bin/mongod --config /etc/mongod.confsystemctl status mongod.service● mongod.service - MongoDB® Database Server Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor prese> Active: active (running) since Tue 2022-03-01 10:43:45 UTC; 2s ago Docs: https://docs.mongodb.org/manual Main PID: 21449 (mongod) Memory: 153.2M CGroup: /system.slice/mongod.service └─21449 /usr/bin/mongod --config /etc/mongod.confPress
qto exit. -
Ensure that the daemon restarts automatically at boot.
systemctl enable mongodsystemctl enable mongod.serviceJun 27 15:36:34 mongoDB systemd[1]: Started High-performance, schema-free document-oriented database.
Testing authentication
-
Connect without credentials to verify that actions are restricted.
mongoshThe following output displays.
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.10.6 Using MongoDB: 7.0.0 Using Mongosh: 1.10.6 For mongosh info see: https://docs.mongodb.com/mongodb-shell/ test>You are now connected to the
testdatabase. -
Test that the access is restricted with the
show dbscommand.show dbsThe following output displays.
MongoServerError: command listDatabases requires authentication
Type exit or press CTRL+C to exit.
Verifying the administrative user's access
-
Connect as an administrator with the
-uoption to supply a username and-pto be prompted for a password. Supply the database where you stored the user's authentication credentials with the--authenticationDatabaseoption.mongosh -u AdminOce -p --authenticationDatabase admin -
Enter your password. The shell displays.
-
Run the
show dbscommand to make sure you are logged in properly.show dbsThe following output displays.
admin 135 kB config 61.4 kB local 73.7 kB
Type exit or press CTRL+C to exit.
Configuring remote access (optional)
Enabling UFW
Uncomplicated Firewall (UFW), is a front-end to iptables. Its main goal is to make managing your firewall drop-dead simple and to provide an easy-to-use interface.
- Install UFW.
apt install ufw - Check UFW status.
ufw status - Enable UFW, as it may be inactive.
ufw enable - Ensure to allow SSH.
ufw allow OpenSSH - Rerun the UFW status command.
An output similar to the following displays.
ufw statusStatus: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) - Allow access to the default MongoDB® port
27017but restrict that access to a specific host.ufw allow from client_ip_address to any port 27017 - Re-run this command using the IP address for each additional client that needs access. To double-check the rule, run
ufw statusagain:An output similar to the following displays.ufw statusTo Action From -- ------ ---- OpenSSH ALLOW Anywhere 27017 ALLOW client_ip_address OpenSSH (v6) ALLOW Anywhere (v6)
Configuring a public bindIP
-
To allow remote connections, add the host's publicly routable IP address to the
mongod.conffile.nano /etc/mongod.conf -
In the
netsection, add the MongoHost's IP to the bindIp line. -
Verify your NAT IP with the
ifconfigcommand.ifconfigAn output similar to the following displays.
net: port: 27017 bindIp: 127.0.0.1,IP_of_MongoHost -
Restart the daemon.
systemctl restart mongod.service -
Check the daemon status.
systemctl status mongod.serviceAn output similar to the following displays.
Active: active (running) since Thu 2018-xx-yy 13:15:35 UTC; 5s ago
Testing remote connections
Ensure that Mongo is listening on its public interface by adding the --host flag with the IP address from the mongodb.conf file.
mongosh -u AdminOce -p --authenticationDatabase admin --host IP_address_of_MongoHostAn output similar to the following displays.
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.10.6
Using MongoDB: 7.0.0
Using Mongosh: 1.10.6
For mongosh info see: https://docs.mongodb.com/mongodb-shell/Uninstalling MongoDB
- Stop MongoDB.
service mongod stop - Remove any MongoDB® packages that you had previously installed.
apt purge mongodb-org* - Remove MongoDB® databases and log files.
rm -r /var/log/mongodb rm -r /var/lib/mongodb
Visit our Help Center and find the answers to your most frequent questions.
Visit Help Center