There is a new version of this tutorial available for Ubuntu 22.04 (Jammy Jellyfish).

How to Install and Configure MongoDB on Ubuntu 18.04 LTS

MongoDB is a NoSQL database that offers high performance, high availability and automatic scaling of the enterprise level database. MongoDB is a NoSQL database, so you cannot use SQL (Structured Query Language) to insert and retrieve data, and it does not store data in tables like MySQL or Postgres. The data is stored in a "document" structure in JSON format (called BSON in MongoDB). MongoDB was introduced in 2009 and is currently being developed by MongoDB Inc.

MongoDB only offers packages for 64-bit LTS (long-term support) Ubuntu versions. For example 14.04 LTS (trusty), 16.04 LTS (xenial), 18.04 LTS (bionic) and so on.

In this tutorial I will install MongoDB 4.0 on Ubuntu 18.04 LTS.

Prerequisites

  • Ubuntu Server 18.04 - 64 bit
  • Root privileges

What we will do in this tutorial:

  1. Install MongoDB
  2. Configure MongoDB
  3. Conclusion

Install MongoDB on Ubuntu 18.04 LTS

Step 1 - Importing the Public Key

GPG keys of the software distributor are required by the Ubuntu package manager apt (Advanced Package Tool) to ensure the consistency and authenticity of the package. Execute this command to import MongoDB keys to your server.

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 68818C72E52529D4

Step 2 - Create source list file MongoDB

Create a MongoDB list file in /etc/apt/sources.list.d/ with this command:

sudo echo "deb http://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list

Step 3 - Update the repository

update the repository with the apt command:

sudo apt-get update

Step 4 - Install MongoDB

Now you can install MongoDB by typing this command:

sudo apt-get install -y mongodb-org

The MongoDB apt installer created a mongod.service file for Systemd automatically, so there is no need to create it manually anymore.

Start MongoDB and add it as a service to be started at boot time:

sudo systemctl start mongod
sudo systemctl enable mongod

Now check that MongoDB has been started on port 27017 with the netstat command.

sudo netstat -plntu

Check if MongoDB is running.

Configure MongoDB username and password

When the MongoDB packages are installed you can configure username and password for the database server:

Step 1 - Open mongo shell

Before you set up a username and password for MongoDB, you need to open the MongoDB shell on your server. You can login by typing:

mongo

If you get error Failed global initialization: BadValue Invalid or no user locale set. Please ensure LANG and/or LC_* environment variables are set correctly, try the command:

export LC_ALL=C
mongo

Step 2 - Switch to the database admin

Once you`re in the MongoDB shell, switch to the database named admin:

use admin

Step 3 - Create the root user

Create the root user with this command :

db.createUser({user:"admin", pwd:"admin123", roles:[{role:"root", db:"admin"}]})

Desc: Create user admin with password admin123 and have the permission/role as root and the database is admin.

Create a admin user in MongoDB

Now type exit to exit from MongoDB shell.

exit

And you are back on the Linux shell.

Step 4 - Enable MongoDB authentication

Edit the mongodb service file '/lib/systemd/system/mongod.service' with your editor.

sudo nano /lib/systemd/system/mongod.service

On the 'ExecStart' line 9, add the new option '--auth'.

ExecStart=/usr/bin/mongod --auth --config /etc/mongod.conf

Save the service file and exit nano.

Reload the systemd service:

sudo systemctl daemon-reload

Step 5 - Restart MongoDB and try to connect

Now restart MongoDB and connect with the user created.

sudo service mongod restart

and connect to the MongoDB shell with this command:

mongo -u admin -p admin123 --authenticationDatabase admin

and you will see the output like this:

Test MongoDB Authentication.

Enable external access and configure the UFW Firewall

UFW is the default firewall in Ubuntu. In this chapter, I will show how to configure UFW to allow external access to MongoDB.

Check the UFW status

sudo ufw status

When the result is: 

Status: inactive

Enable UFW with this command and open the SSH port first if connected by SSH:

sudo ufw allow ssh
sudo ufw enable

before you proceed with the next steps.

For security reasons, you should allow access to the MongoDB port 27017 only from IP addresses that need to access the database. By default, localhost is always able to access it, so no need to open the MongoDB port for IP 127.0.0.1.

UFW Firewall Syntax

sudo ufw allow from <target> to <destination> port <port number>

Open MongoDB Port in UFW

To allow access from external IP 192.168.1.10 to MongoDB, use this command:

sudo ufw allow from 192.168.1.10 to any port 27017

Replace the IP address in the above command with the external Ip you want to allow access to MongoDB.

If you want to open the MongoDB port for any IP, e.g. in case you run it in a local network and all systems in that network shall be able to access MongoDB, then use this command:

sudo ufw allow 27017

Check the status of the UFW firewall with this command:

sudo ufw status

MongoDB listens to localhost by default, to make the database accessible from outside, we have to reconfigure it to listen on the server IP address too.

Open the mongod.conf file in nano editor:

sudo nano /etc/mongod.conf

and add the IP address of the server in the bind_ip line like this:

# network interfaces
net:
port: 27017
bindIp: 127.0.0.1,192,168.1.100

Replace 192.168.1.100 with the IP of your server, then restart MongoDB to apply the changes.

sudo service mongod restart

Now you can access the MongoDB database server over the network.

Virtual Machine image

This tutorial is available as a ready to use virtual machine in OVA / OVF format for Howtoforge subscribers. The VM format is compatible with VMWare and Virtualbox and other tools that can import the ova or ovf format. You can find the download link in the right menu on the top. Click on the filename to start the download.

The login details of the VM are:

SSH Login

Username: administrator
Password: howtoforge

The administrator user has sudo permissions.

Please change the passwords after the first boot.

The VM is configured for the static IP 192.168.1.100. Instructions on how to change the static IP can be found here.

Conclusion

MongoDB is a well-known NoSQL database that offers high performance, high availability and automatic scaling. It differs from RDBMS such as MySQL, PostgreSQL and SQLite because it does not use SQL to set and retrieve data. MongoDB stores data in `documents` called BSON (binary representation of JSON with additional information). MongoDB is only available for the 64-bit long-term support Ubuntu release.

Share this page:

20 Comment(s)

Add comment

Please register in our forum first to comment.

Comments

By: Alex

Excellent guide, very easy!, thank you!

By: Freek

How can I install version 3.2.19 on Ubuntu 18?

By: David Sol

I can't install the enterprise edition in Ubuntu 18.04 because of a conflict between libcurl3 and libcurl4:

sudo apt-get install mongodb-enterprise-server

Reading package lists... Done

Building dependency tree       

Reading state information... Done

Some packages could not be installed. This may mean that you have

requested an impossible situation or if you are using the unstable

distribution that some required packages have not yet been created

or been moved out of Incoming.

The following information may help to resolve the situation:

 

The following packages have unmet dependencies:

 mongodb-enterprise-server : Depends: libcurl3 (>= 7.16.2) but it is not going to be installed

E: Unable to correct problems, you have held broken packages.

Seems it is a problem affecting several 3rd party applications.

Maybe you can fix it when you make the bionic repository?

Thanks

By: Benjamin Balogun

Workaround is to replace libcurl4 with libcurl3, so

sudo apt-get install -y libcurl3

that should get functional version then 

sudo apt-get install -y xxxx

where xxxx is all other depends that arise, that should install them correctly

then once no more unmet dependencies go back and run your mongodb-org

sudo apt-get install -y mongodb-org

or whichever one you used before that gave the initial error

 

By: David Sol

Thanks, but... wouldn't that "break" all other programs that depend on libcurl4?

By: Ashish

Reading package lists... Done Building dependency tree        Reading state information... Done libcurl4 is already the newest version (7.58.0-2ubuntu3.3). libcurl4 set to manually installed. You might want to run 'apt --fix-broken install' to correct these. The following packages have unmet dependencies: mongodb-org-server : Depends: libcurl3 (>= 7.16.2) but it is not going to be installed E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).

 

 

This is what i find every now  and then.. help!

By: Shashika

Superb tutorial... made my work so easy..!!!

By: BartNg

It's work for me,thank you!

By: Josh

I have used this like 10 times to set up mongo. Great info and concise!

By: Herbert

Exellent tutorial keep it please

By: ftw

thnks you, excellent guide about configure a root user on mongodb. was very helpfull

By: Sudheeran

Nice article,thank you ...

By: Sunny

after this my node.js server running on port 80 is not accessible anymore! 

tcp        0      0 127.0.0.1:80            0.0.0.0:*               LISTEN      5511/node

Also restarted the server.. run on tcp6 and back.. not accessible anymore - why and how to solve this?

By: Burk

Excellent guide, thank you!

By: mostafa

dude this is the best tutorial, for folks with filtered websites, just connect to a proxy VPN and try to inistall again. 

By: natalia

Thanks a lot! great guide. Keep it up!

By: bhadra

# network interfacesnet:  port: 27017  bindIp: 127.0.0.1,192,183.82.119.115# service mongod restart

#[email protected]:~# sudo service mongod status? mongod.service - MongoDB Database Server   Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: e   Active: failed (Result: exit-code) since Thu 2019-11-14 05:37:36 UTC; 12s ago     Docs: https://docs.mongodb.org/manual  Process: 3018 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=exited Main PID: 3018 (code=exited, status=48)Nov 14 05:37:35 ip-172-31-27-110 systemd[1]: Started MongoDB Database Server.Nov 14 05:37:36 ip-172-31-27-110 systemd[1]: mongod.service: Main process exitedNov 14 05:37:36 ip-172-31-27-110 systemd[1]: mongod.service: Failed with [email protected]:~# vi /etc/mongod.conf

 

By: Shubham

I have followed the steps but still getting this error msg, i have uninstalled and reisntalled many times but it seems like the below error still persist.

 

Any thougts ?

Error Log 

 

mongodb.service - High-performance, schema-free document-oriented >database

   Loaded: loaded (/etc/systemd/system/mongodb.service; enabled; vendor preset: enabled)

   Active: failed (Result: exit-code) since Mon 2019-11-25 17:34:09 IST; 6s ago

  Process: 16617 ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf (code=exited, status=2)

 Main PID: 16617 (code=exited, status=2)

 

Nov 25 17:34:09 shubham-HP-Laptop-15g-br0xx systemd[1]: Started High-performa…e.

Nov 25 17:34:09 shubham-HP-Laptop-15g-br0xx mongod[16617]: Error reading conf…ry

Nov 25 17:34:09 shubham-HP-Laptop-15g-br0xx mongod[16617]: try '/usr/bin/mong…on

Nov 25 17:34:09 shubham-HP-Laptop-15g-br0xx systemd[1]: mongodb.service: Main…NT

Nov 25 17:34:09 shubham-HP-Laptop-15g-br0xx systemd[1]: mongodb.service: Fail…'.

Hint: Some lines were ellipsized, use -l to show in full.

 

By: Pete

Nope, did not work.

 

Followed all the steps as listed, but it failed when trying to install using this command.....

sudo apt-get install mongodb-org

Reading package lists... Done

Building dependency tree       

Reading state information... Done

Some packages could not be installed. This may mean that you have

requested an impossible situation or if you are using the unstable

distribution that some required packages have not yet been created

or been moved out of Incoming.

The following information may help to resolve the situation:

 

The following packages have unmet dependencies:

 mongodb-org : Depends: mongodb-org-shell but it is not going to be installed

               Depends: mongodb-org-server but it is not going to be installed

               Depends: mongodb-org-mongos but it is not going to be installed

E: Unable to correct problems, you have held broken packages.

 

 

By: Luis Ramirez

Thanks !!!! 

 

Very good