Hometutorials
setup mongodb on ubuntu

Jump toUpdate content

Installing and Securing MongoDB on Ubuntu Focal Fossa (20.04)

Reviewed on 01 March 2022Published on 01 March 2022
  • database
  • compute
  • mysql
  • mongoDB
  • UFW
  • bindIP

MongoDB is a document-oriented database that is free and open-source. It is considered one of the most popular NoSQL database engines because it is scalable, robust, reliable, and easy to use. In contrast to a relational database, MongoDB does not require a deep predefined schema before you can add data since it can be altered at any time. As it uses the NoSQL concept, data rows are stored in JSON-like documents, allowing arbitrary data to be inserted.

Requirements:

Setting up MongoDB

Adding MongoDB repository

Important:

You should always use the official MongoDB mongodb-org packages, to make sure you have the latest, up-to-date major and minor MongoDB releases.

  1. Connect to your instance via SSH.

    ssh root@your.instance.ip.address

    If you do not know your server IP, you can list your existing servers using the Scaleway CLI scw instance server list.

    Tip:

    If you use the root user, you can remove the sudo before each command.

  2. Update the Ubuntu package manager.

    sudo apt update
  3. Upgrade the Ubuntu packages already installed.

    sudo apt upgrade
  4. Import the key for the official MongoDB repository (Ubuntu ensures the authenticity of software packages by verifying that they are signed with GPG keys.).

    wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -

    The command above should respond with an OK.

  5. Add the MongoDB repository details so that Ubuntu’s apt command-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 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list
  6. Update the packages list

    sudo apt update

Installing MongoDB

  1. Install the mongodb-org meta-package, which includes the daemon, configuration and init scripts, shell, and management tools on the server.

    sudo apt install mongodb-org
  2. Press enter or type Y to proceed when prompted. Once the installation is completed, start the MongoDB daemon.

    sudo systemctl start mongod
  3. Since systemctl does not provide output, verify that the service has started properly.

    sudo 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:36:39 UTC; 1s ago
    Docs: https://docs.mongodb.org/manual
    Main PID: 21330 (mongod)
    Memory: 59.7M
    CGroup: /system.slice/mongod.service
    └─21330 /usr/bin/mongod --config /etc/mongod.conf

    Press q to exit.

  4. Ensure that it restarts automatically at each boot

    sudo systemctl enable mongod
    Created 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 could create and destroy databases, as well as read from and write to their contents by default. To secure MongoDB, we need to create an administrative user and enable authentication.

  1. Connect to the Mongo shell to add a new user.

    mongosh
    Current Mongosh Log ID: 621df7b9edede63d1ce01d10
    Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.2.2
    Using MongoDB: 5.0.6
    Using Mongosh: 1.2.2

    For mongosh info see: https://docs.mongodb.com/mongodb-shell/

To help improve our products, anonymous usage data is collected and sent to MongoDB periodically (https://www.mongodb.com/legal/privacy-policy). You can opt-out by running the disableTelemetry() command.


You can choose any preferred name for the administrative user since the privilege level is assigned from the role of `userAdminAnyDatabase`.

The `admin` database designates where the credentials are stored. You can learn more about authentication in the [MongoDB Security Authentication section](https://docs.mongodb.com/manual/core/authentication/).

2. Set the username of your choice and be sure to pick your own secure password and 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 }


3. Type `exit` and press ENTER or use `CTRL+C` to leave the client.

admin> exit


### Enabling authentication

In order to enforce authentication, we need to enable authentication and restart the MongoDB daemon.

1. Open the configuration file.

sudo nano /etc/mongod.conf


2. Remove the hash in front of `security` to enable the section. Then, we add the authorization lines (indented with two spaces) as per the following excerpt below:

security: authorization: “enabled”


3. Restart the daemon.

sudo systemctl restart mongod


4. Check the status to verify that the service has rebooted.

sudo 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.conf


Press `q` to exit.

5. Ensure that the daemon restarts automatically at boot.

sudo systemctl enable mongod


If we see Active: `active (running)` in the output and it ends with something similar to the text below, the restart command was successful:

Jun 27 15:36:34 mongoDB systemd[1]: Started High-performance, schema-free document-oriented database.


### Testing authentication

1. Connect without credentials to verify that our actions are restricted

mongosh


Current Mongosh Log ID: 621df910e27c7cc01630033b Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.2.2 Using MongoDB: 5.0.6 Using Mongosh: 1.2.2

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

test>


We are connected to the `test` database.

2. Test that the access is restricted with the `show dbs` command:

test> show dbs MongoServerError: command listDatabases requires authentication


3. Exit the shell to proceed.

exit bye


Verifying the administrative user’s access

  1. Connect as our administrator with the -u option to supply a username and -p to be prompted for a password. Supply the database where we stored the user’s authentication credentials with the --authenticationDatabase option.

    mongosh -u AdminOce -p --authenticationDatabase admin
  2. Once the correct password is entered, we are dropped into the shell, where we can issue the show dbs command:

    test> show dbs
    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.

Note: If UFW is already installed on your computer, go directly to step 5.
  1. Install UFW.

    sudo apt install ufw
  2. Check UFW status.

    sudo ufw status
  3. Enable UFW, as it is probably inactive.

    sudo ufw enable
  4. Ensure to allow SSH.

    sudo ufw allow OpenSSH
  5. Rerun the UFW status command.

    sudo ufw status
    Status: active

    To Action From
    -- ------ ----
    OpenSSH ALLOW Anywhere
    OpenSSH (v6) ALLOW Anywhere (v6)
  6. Allow access to the default MongoDB port 27017 but restrict that access to a specific host.

    sudo ufw allow from client_ip_address to any port 27017
  7. Re-run this command using the IP address for each additional client that needs access. To double-check the rule, run ufw status again:

    sudo ufw status
    To                         Action      From
    -- ------ ----
    OpenSSH ALLOW Anywhere
    27017 ALLOW client_ip_address
    OpenSSH (v6) ALLOW Anywhere (v6)

Configuring a public bindIP

  1. To allow remote connections, add our host’s publically-routable IP address to the mongod.conf file.

    sudo nano /etc/mongod.conf
  2. In the net section, add the MongoHost’s IP to the bindIp line.

    Note:

    Verify your private IP with the ifconfig command.

    net:
    port: 27017
    bindIp: 127.0.0.1,IP_of_MongoHost
  3. Restart the daemon.

    systemctl restart mongod
  4. Check the daemon status.

    systemctl status mongod
    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_MongoHost
Current Mongosh Log ID: 621df9af8745805d6c99e48c
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.2.2
Using MongoDB: 5.0.6
Using Mongosh: 1.2.2Current Mongosh Log ID: 621df9af8745805d6c99e48c

Uninstalling MongoDB

Important:

This process will completely remove MongoDB, its configuration, and all databases. This process is not reversible, so ensure that all of your configuration and data is backed up before proceeding.

  1. Stop MongoDB.

    sudo service mongod stop
  2. Remove any MongoDB packages that you had previously installed.

    sudo apt purge mongodb-org*
  3. Remove MongoDB databases and log files.

    sudo rm -r /var/log/mongodb
    sudo rm -r /var/lib/mongodb