Sunday, May 9, 2021

How To Install MongoDB from the Default APT Repositories on Ubuntu 20.04

 

Introduction

MongoDB is a free and open-source NoSQL document database used commonly in modern web applications.

In this tutorial you’ll install MongoDB, manage its service, and optionally enable remote access.

Note: As of this writing, this tutorial installs version 3.6 of MongoDB, which is the version available from the default Ubuntu repositories. However, we generally recommend installing the latest version of MongoDB — version 4.4 as of this writing — instead. If you’d like to install the latest version of MongoDB, we encourage you to follow this guide on How To Install MongoDB on Ubuntu 20.04 from source.

Prerequisites

To follow this tutorial, you will need:

  • One Ubuntu 20.04 server set up by following this initial server setup tutorial, including a non-root user with administrative privileges and a firewall configured with UFW.

Step 1 — Installing MongoDB

Ubuntu’s official package repositories include MongoDB, which means we can install the necessary packages using apt. As mentioned in the introduction, the version available from the default repositories is not the latest one. To install the latest version of Mongo, please follow this tutorial instead.

First, update the packages list to have the most recent version of the repository listings:

  • sudo apt update
 

Now install the MongoDB package itself:

  • sudo apt install mongodb
 

This command will prompt you to confirm that you want to install the mongodb package and its dependencies. To do so, press Y and then ENTER.

This command installs several packages containing a stable version of MongoDB, along with helpful management tools for the MongoDB server. The database server is automatically started after installation.

Next, let’s verify that the server is running and works correctly.

Step 2 — Checking the Service and Database

The installation process started MongoDB automatically, but let’s verify that the service is started and that the database is working.

First, check the service’s status:

  • sudo systemctl status mongodb
 

You’ll see this output:

Output
● mongodb.service - An object/document-oriented database Loaded: loaded (/lib/systemd/system/mongodb.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2020-10-08 14:23:22 UTC; 49s ago Docs: man:mongod(1) Main PID: 2790 (mongod) Tasks: 23 (limit: 2344) Memory: 42.2M CGroup: /system.slice/mongodb.service └─2790 /usr/bin/mongod --unixSocketPrefix=/run/mongodb --config /etc/mongodb.conf

According to this output, the MongoDB server is up and running.

We can verify this further by actually connecting to the database server and executing the following diagnostic command. This will output the current database version, the server address and port, and the output of the status command:

  • mongo --eval 'db.runCommand({ connectionStatus: 1 })'
 
Output
MongoDB shell version v3.6.8 connecting to: mongodb://127.0.0.1:27017 Implicit session: session { "id" : UUID("e3c1f2a1-a426-4366-b5f8-c8b8e7813135") } MongoDB server version: 3.6.8 { "authInfo" : { "authenticatedUsers" : [ ], "authenticatedUserRoles" : [ ] }, "ok" : 1 }

A value of 1 for the ok field in the response indicates that the server is working properly.

Next, we’ll look at how to manage the server instance.

Step 3 — Managing the MongoDB Service

The installation process outlined in Step 1 configures MongoDB as a systemd service, which means that you can manage it using standard systemctl commands alongside all other system services in Ubuntu.

To verify the status of the service, type:

  • sudo systemctl status mongodb
 

You can stop the server at any time by typing:

  • sudo systemctl stop mongodb
 

To start the server when it is stopped, type:

  • sudo systemctl start mongodb
 

You can also restart the server with the following command:

  • sudo systemctl restart mongodb
 

By default, MongoDB is configured to start automatically with the server. If you wish to disable the automatic startup, type:

  • sudo systemctl disable mongodb
 

You can re-enable automatic startup any time with the following command:

  • sudo systemctl enable mongodb
 

Next, let’s adjust the firewall settings for our MongoDB installation.

Step 4 — Adjusting the Firewall (Optional)

Assuming you have followed the initial server setup tutorial instructions to enable the firewall on your server, the MongoDB server will be inaccessible from the internet.

If you intend to use the MongoDB server only locally with applications running on the same server, this is the recommended and secure setting. However, if you would like to be able to connect to your MongoDB server from the internet, you have to allow the incoming connections by adding a UFW rule.

To allow access to MongoDB on its default port 27017 from everywhere, you could run sudo ufw allow 27017. However, enabling internet access to MongoDB server on a default installation gives anyone unrestricted access to the database server and its data.

In most cases, MongoDB should be accessed only from certain trusted locations, such as another server hosting an application. To only allow access to MongoDB’s default port by another trusted server, you can specify the remote server’s IP address in the ufw command. This way, only that machine will be explicitly allowed to connect:

  • sudo ufw allow from trusted_server_ip/32 to any port 27017
 

You can verify the change in firewall settings with ufw:

  • sudo ufw status
 

You should see traffic to port 27017 allowed in the output. Note that if you have decided to allow only a certain IP address to connect to MongoDB server, the IP address of the allowed location will be listed instead of Anywhere in this command’s output:

Output
Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere 27017 ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) 27017 (v6) ALLOW Anywhere (v6)

You can find more advanced firewall settings for restricting access to services in UFW Essentials: Common Firewall Rules and Commands.

Even though the port is open, MongoDB will still only be listening on the local address 127.0.0.1. To allow remote connections, add your server’s publicly-routable IP address to the mongodb.conf file.

Open the MongoDB configuration file in your preferred text editor. This example command uses nano:

  • sudo nano /etc/mongodb.conf
 

Add your MongoDB server’s IP address to the bindIP value. Be sure to place a comma between the existing IP address and the one you added:

/etc/mongodb.conf
...
logappend=true

bind_ip = 127.0.0.1,your_server_ip
#port = 27017

...
 

Save the file and exit the editor. If you used nano to edit the file, do so by pressing CTRL + XY, then ENTER.

Then, restart the MongoDB service:

  • sudo systemctl restart mongodb
 

MongoDB is now listening for remote connections, but anyone can access it. Follow How To Secure MongoDB on Ubuntu 20.04 to add an administrative user and lock things down further.

Conclusion

You can find more in-depth tutorials on how to configure and use MongoDB in these DigitalOcean community articles. The official MongoDB documentation is also a great resource on the possibilities that MongoDB provides.

Install MongoDB

 Author: MongoDB Documentation Team

This guide describes how to install MongoDB locally. If you would like to use MongoDB in the Cloud using Atlas, our managed database product, see Get Started with Atlas.

Time required: 10 minutes

What You’ll Need

MongoDB supports a variety of 64-bit platforms. Refer to the Supported Platforms table to verify that MongoDB is supported on the platform to which you wish to install it.

Procedure

Install MongoDB

NOTE

These instructions are for installing MongoDB directly from an archive file. If you would rather use your linux distribution’s package manager, refer to the installation instructions for your distribution in the MongoDB Manual.

1

Download the binary files for the desired release of MongoDB.

Download the binaries from the MongoDB Download Center.

2

Extract the files from the downloaded archive.

Extract the archive by double-clicking on the tar file or using the tar command from the command line, as in the following:

tar -xvzf <tgz file>
3

Copy the extracted archive to the target directory.

Copy the extracted folder to the location from which MongoDB will run.

4

Ensure the location of the binaries is in the PATH variable.

The MongoDB binaries are in the bin/ directory of the archive. To ensure that the binaries are in your PATH, you can modify your PATH.

For example, you can add the following line to your shell’s rc file (e.g. ~/.bashrc):

export PATH=<mongodb-install-directory>/bin:$PATH

Replace <mongodb-install-directory> with the path to the extracted MongoDB archive.

Run MongoDB

IMPORTANT

If you are using SELinux on a Red Hat Linux-based system, (Red Hat Enterprise Linux or CentOS Linux), you must configure SELinux to allow MongoDB to start. Refer to Configure SELinux for instructions.

1

Create the data directory

Before you start MongoDB for the first time, create the directory to which the mongod process will write data. By default, the mongod process uses the /data/db directory. If you create a directory other than this one, you must specify that directory in the dbpath option when starting the mongod process later in this procedure.

The following example command creates the default /data/db directory:

mkdir -p /data/db
2

Set permissions for the data directory

Before running mongod for the first time, ensure that the user account running mongod has read and write permissions for the directory.

sudo chown -R $USER:$USER /data/

3

Run MongoDB

To run MongoDB, run the mongod process at the system prompt. If necessary, specify the path of the mongod or the data directory. See the following examples.

Run without specifying paths

If your system PATH variable includes the location of the mongod binary and if you use the default data directory (i.e., /data/db), simply enter mongod at the system prompt:

mongod
Specify the path of the mongod

If your PATH does not include the location of the mongod binary, enter the full path to the mongod binary at the system prompt:

<path to binary>/mongod
Specify the path of the data directory

If you do not use the default data directory (i.e., /data/db), specify the path to the data directory using the --dbpath option:

mongod --dbpath <path to data directory>
4

Verify that MongoDB has started successfully

Verify that MongoDB has started successfully by checking the process output for the following line:

[initandlisten] waiting for connections on port 27017

The output should be visible in the terminal or shell window.

You may see non-critical warnings in the process output. As long as you see the log line shown above, you can safely ignore these warnings during your initial evaluation of MongoDB.

Summary

If you have successfully completed this guide, you have installed MongoDB and are ready to connect to your mongod instance and start inserting data.