How to Install MongoDB on Ubuntu 18.04

In this article, we will show you how to install MongoDB, manage its services, and allow remote connections on an Ubuntu 18.04 VPS.

MongoDB is an open-source database management system that belongs to a family of NoSQL. NoSQL is different from traditional table-based SQL databases (MySQL and PostgreSQL) – the data is stored in flexible JSON-like documents with no pre-defined schema, which allows for large changes to be made to databases with no downtime. Let’s get started with the installation.

Step 1: Connect to your Server

Before we begin, you need to connect to your server via SSH as the root user. To do this, use the following command:

ssh root@IP_Address -p port_number

You will need to replace IP_Address and port_number with your actual server IP address and SSH port number. If you don’t have access to the root account, you can use an account with sudo privileges instead.

Once logged in, make sure that your server is up-to-date by running the following commands:

sudo apt update
sudo apt upgrade

Step 2: Installing MongoDB

Ubuntu official software package repositories come with version 3.6.3 of MongoDB, but in this article, we will install MongoDB 4.0 which is the latest available version. However, you can always check if a new version of MongoDB is available on their official website.

In order to install the MongoDB 4.0 Community Edition on Ubuntu, we need to import the public key used by the package management system. We can do that with the following command:

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4

Since we have the key imported now, we can add the MongoDB repository with this next line:

sudo add-apt-repository 'deb [arch=amd64] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.0 multiverse'

We then update the packages list:

sudo apt update

At this point, the repository is enabled and packages list is updated – we can now continue with installing the MongoDB CE package by entering the following command:

sudo apt install mongodb-org

The mongodb-org-server, mongodb-org-mongos, mongodb-org-shell and mongodb-org-tools packages will be installed on your system as a part of the mongodb-org package.

The MongoDB 4.0 Community Edition is now installed on the server. We then need to start the MongoDB service and enable it to start on boot.

sudo systemctl start mongod
sudo systemctl enable mongod

To verify the MongoDB installation, we can check the connection status by typing the command:

mongo --eval 'db.runCommand({ connectionStatus: 1 })'

You should have an output similar to this:

MongoDB shell version v4.0.6
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("c806e0e1-ab30-4d41-b882-026c09d2893f") }
MongoDB server version: 4.0.6
{
"authInfo" : {
"authenticatedUsers" : [ ],
"authenticatedUserRoles" : [ ]
},
"ok" : 1
}

Congratulations, you have successfully installed MongoDB on your server. The next step will go over configuring your MongoDB server.

Step 3: Configuring MongoDB

We can configure the MongoDB instance by modifying the mongod.conf file, located in /etc/. We’ll use Nano to edit the file, but you can use your preferred text editor if you like.

sudo nano /etc/mongod.conf

In order to allow remote connections and better secure MongoDB, we will make some changes in the configuration file. MongoDB by default listens for connections on port 27017 on localhost (IP 127.0.0.1) only. In order to allow a remote MongoDB connection, you need to add your server IP address to the MongoDB configuration file. This is shown as an example below:

bind_ip = 127.0.0.1, your_server_ip
#port = 27017

security:
authorization: enabled

We also included an authorization option that will regulate user access to MongoDB databases. If the authorization option is not enabled, then each user will have access to all the MongoDB databases and can perform any action, which is a security risk. After we save the changes in the MongoDB configuration file, we need to restart the MongoDB service with the following command for the changes to take effect:

sudo systemctl restart mongod

Step 4: Creating Administrative MongoDB User

Since we configured the MongoDB server and enabled the authentication option, we now need to create an administrative MongoDB user account which will be used to manage the MongoDB instance.

To access the mongo shell, type:

mongo

Next, we will use the following command to connect to the admin database:

use admin

Output:

switched to db admin

We will perform the following command to create a new administrative user called mongo_admin with the userAdminAnyDatabase role:

db.createUser(
{
user: "mongo_admin", 
pwd: "Strong_Pas$w0rd", 
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)

And we will get this as output:

Successfully added user: {
"user" : "mongo_admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}

Don’t forget to replace ‘Strong_Pas$w0rd’ with an actual strong password. We can now exit the mongo shell:

quit()

Step 5: Verifying the Administrative User’s Access

To confirm the changes, we will access the mongo shell using the mongo_admin user we created:

mongo -u mongo_admin -p --authenticationDatabase admin

use admin

show users

And if you followed all of the steps so far, you should have the following output:

Output:

> use admin
switched to db admin
> show users
{
"_id" : "admin.mongo_admin",
"user" : "mongo_admin",
"db" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}

You can also try to list the users when you access the mongo shell (without arguments) and use the same commands as we used before.

Step 6: Allow Remote MongoDB Access in the Firewall

In this step, we will provide remote access to our MongoDB by allowing it in our firewall. If you do not use any firewall on your server, you can skip this step. The default port of MongoDB is 27017, so in our examples, we’ll show you how to allow this port through your firewall.

If you are using the UFW (Uncomplicated Firewall) then you can use the following tips on how to allow MongoDB to be remotely accessible.

To allow access to MongoDB on its default port (27017) from everywhere, you can use the following command:

sudo ufw allow 27017

To allow access to MongoDB on its default port 27017 from a specific IP address only, you can use the command:

sudo ufw allow from allowed_IP_address/32 to any port 27017

You will need to change allowed_IP_address with the actual IP address that you want to use.

You can confirm the change to the firewall settings with:

sudo ufw status

Output:

Status: active

To                         Action      From
--                         ------      ----
27017                      ALLOW       Anywhere
OpenSSH                    ALLOW       Anywhere
27017 (v6)                 ALLOW       Anywhere (v6)
OpenSSH (v6)               ALLOW       Anywhere (v6)

Step 7: Connect to MongoDB

Now that we installed and configured MongoDB, we need to mention a few different ways on how to connect to it. We need to make sure that our MongoDB configuration works before we attempt to access the Mongo shell.

Local MongoDB Instance on Default Port

The most basic connection to the mongo shell is just running the mongo command without any arguments:

mongo

Local MongoDB Instance on a Non-default Port

If we want to connect to the Mongo shell on a specific port then we can use:

mongo --port port_number

Just replace the port_number with your actual port number.

MongoDB Instance on a Remote Host

If we need to connect to a remote host machine with the MongoDB instance, we can use the following ways:

We can specify a connection string.

mongo mongodb://your_domain_name.com:port_number

We can use the command-line option –host <host>:<port>

mongo --host your_domain_name.com:port_number

or we can use the –host <host> and –port <port>

mongo --host your_domain_name.com --port port_number

MongoDB Instance with Authentication

We will use these examples to show you how to connect to a MongoDB instance that requires authentication.

We can define the username, authentication database and the port number in our connection string. Also, we can define the password (which is optional) in our connection string. If the password is not defined in our connection string then the shell will prompt for the password.

mongo --host mongodb://user@your_domain_name.com:port_number/?authSource=admin

We can use the –username <user>, –password, and –authenticationDatabase <db> command-line options.

mongo --username user --password --authenticationDatabase admin --host your_domain_name.com --port port_number

Connect to a MongoDB Replica Set

We can specify the replica set name and members in the connection string.

mongo mongodb://your_domain_name.com.local:port_number,mongodb1.your_domain_name.com.local:port_number,mongodb2.your_domain_name.com.local:port_number/?replicaSet=replA

If you are using the DNS Seedlist Connection Format, you can specify the connection string:

mongo "mongodb+srv://server.your_domain_name.com/"

We can specify the replica set name and members from the –host <replica set name>/<host1>:<port1>,<host2>:<port2>,… In this example to connect to a replica set named replA:

mongo --host replA/your_domain_name.com.local:port_number,mongodb1.your_domain_name.com.local:port_number,mongodb2.your_domain_name.com.local:port_number

TLS/SSL Connection

We can specify the ssl=true option in the connection string.

mongo mongodb://your_domain_name.com.local:port_number,mongodb1.your_domain_name.com.local:port_number,mongodb2.your_domain_name.com.local:port_number/?replicaSet=replA&ssl=true

or we can specify –ssl in the command line and use the previous example on how to connect to the replica set named replA:

mongo --ssl --host replA/your_domain_name.com.local:port_number,mongodb1.your_domain_name.com.local:port_number,mongodb2.your_domain_name.com.local:port_number

If you want to use the above commands, don’t forget to replace the values like your_domain_name.com, host_name, user, and replA in the commands with the actual values.

Step 8: Uninstall MongoDB

If for any reason you do not like MongoDB and you need to remove it from your system, you can follow these commands:

sudo service mongod stop
sudo apt purge mongodb-org*
sudo rm -r /var/log/mongodb
sudo rm -r /var/lib/mongodb

In this article, we showed you how to install MongoDB, customize the firewall, create an admin user, enable remote access, connect to MongoDB and how to uninstall and remove MongoDB. Now you can use this knowledge and can start with building your projects in this wonderful application.


Of course, if you are one of our Ubuntu Hosting customers, or if you have one of our Managed MongoDB Hosting plans, you don’t have to install MongoDB on your Ubuntu 18.04 VPS – simply ask our admins, sit back, and relax. Our admins will install MongoDB on Ubuntu 18.04 for you immediately.

PS. If you liked this post about how to install MongoDB on an Ubuntu 18.04 VPS, please share it with your friends on the social networks using the buttons below, or simply leave a comment in the comments section. Thanks.

New version available here: How to Install MongoDB on Ubuntu 20.04 and CentOS 8.

Leave a Comment