How to Install MongoDB on Ubuntu (4 Steps)

MongoDB is a NoSQL database and an open-source that offers a high performance, high availability, and automatic scaling enterprise database.

We can't use SQL (Structured Query Language) to create, retrieve,update and delete data (CRUD), and it does not store data in tables like MySQL or Oracle. Data is stored in a "document" structure in JSON format (in MongoDB called BSON) which a record is a document.

In this article, we will explain how to install MongoDB, manage its service and setup basic authentication on Ubuntu 18.04.

Important: You should note that company MongoDB Inc only offer packages for 64-bit LTS (long-term support) Ubuntu releases such as 14.04 LTS (trusty), 16.04 LTS (xenial), 18.04 LTS (bionic) and so on.

Step 1) Installing MongoDB on Ubuntu 18.04

Ubuntu's official package repositories comes with the latest version of MongoDB, which means we can install the necessary packages using apt-get.

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

$ sudo apt-get update

we will install MongoDB package that includes several other packages such as mongo-tools, mongodb-clients, mongodb-server and mongodb-server-core.

$ sudo apt-get install -y mongodb

Step 2) Checking the Service and Database of MongoDB

The MongoDB service will start automatically via systemd and the process listens on port 27017. You can verify its status using the systemctl command as shown below.

$ sudo systemctl status mongodb
output
 mongodb.service - An object/document-oriented database
   Loaded: loaded (/lib/systemd/system/mongodb.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2018-08-06 13:16:20 UTC; 6min ago
     Docs: man:mongod(1)
 Main PID: 14415 (mongod)
    Tasks: 23 (limit: 1112)
   CGroup: /system.slice/mongodb.service
           └─14415 /usr/bin/mongod --unixSocketPrefix=/run/mongodb --config /etc/mongodb.conf

Aug 06 13:16:20 li34-72 systemd[1]: Started An object/document-oriented database.

Also we can verify this Installing by connecting to the database server and executing a diagnostic command.

$ mongo --eval 'db.runCommand({ connectionStatus: 1 })'
output
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.3
{
        "authInfo" : {
                "authenticatedUsers" : [ ],
                "authenticatedUserRoles" : [ ]
        },
        "ok" : 1
}

As we see a value of 1 for the ok field in the response indicates that the server is working properly.

Step 3) Managing the MongoDB Service

The MongoDB installation comes as a systemd service and can be easily manageable via a standard systemd commands as shown below.

To stop running MongoDB service, run the following command.

$ sudo systemctl stop mongodb

To start a MongoDB service, type the following command.

$ sudo systemctl start mongodb

To restart a MongoDB service, type the following command.

$ sudo systemctl restart mongodb

To disable automatically started MongoDB service, type the following command.

$ sudo systemctl disable mongodb

To enable again MongoDB service, type the following command.

$ sudo systemctl enable mongodb

Step 4) Adjusting Firewall To Access MongoDB Remotely

If we would like to be able to connect to our MongoDB server from the internet, we have to allow the incoming connections in ufw.

By default MongoDB runs on port 27017, to allow access from everywhere we can type the command below.

$ sudo ufw allow 27017

But it’s better to give access to specific IP address location to default MongoDB’s port using the command below.

$ sudo ufw allow from our_server_IP/32 to any port 27017

By default, UFW is disabled so you should see something like this:

Output:
Status: inactive

To enable ufw type command below.

$ sudo ufw enable

To verify the change in firewall settings with ufw type command below.

$ sudo ufw status
Output:
Status: active

To                         Action      From
--                         ------      ----
27017                      ALLOW       72.14.177.72

By default the port 27017 listens on the local address 127.0.0.1 only. To allow remote MongoDB connections, we need to add our server IP address to /etc/mongodb.conf configuration file as shown below.

$ sudo nano /etc/mongodb.conf
  bind_ip = 127.0.0.1,our_server_ip
  #port = 27017

Finally, we restart the MongoDB.

$ sudo systemctl restart mongodb

Step 4) Create MongoDB Database Root User and Password

To launch the mongo shell, run the following command.

$ sudo mongo

We can list all available databases with the following command.

> show dbs
output:
admin   0.000GB
config  0.000GB
local   0.000GB

We need to create a user administrator as to root user under MySQL/MariaDB in the admin database. This user can administrate users and roles such as create users, grant or revoke roles from users, and create or modify customs roles.

First switch to the admin database, then create the root user using following commands.

  > use admin
  > db.createUser({user:"root", pwd:"pass123", roles:[{role:"root", db:"admin"}]})
  output:
  Successfully added user: {
          "user" : "root",
          "roles" : [
                  {
                          "role" : "root",
                          "db" : "admin"
                  }
          ]
  }

Now exit the mongo shell by typing Ctrl + c to enable authentication.

We need to enable authentication of users by editing /lib/systemd/system/mongod.service file, First open the file for editing.

$ sudo nano /lib/systemd/system/mongodb.service

Under the [Service] config section, find the parameter ExecStart.

ExecStart=/usr/bin/mongod --unixSocketPrefix=${SOCKETPATH} --config ${CONF} $DAEMON_OPTS

And change it to the following:

ExecStart=/usr/bin/mongod --auth --unixSocketPrefix=${SOCKETPATH} --config ${CONF} $DAEMON_OPTS
  /lib/systemd/system/mongodb.service
  ............
  [Service]
  User=mongodb
  Group=mongodb
  RuntimeDirectory=mongodb
  RuntimeDirectoryMode=0755
  EnvironmentFile=-/etc/default/mongodb
  Environment=CONF=/etc/mongodb.conf
  Environment=SOCKETPATH=/run/mongodb
  ExecStart=/usr/bin/mongod --auth --unixSocketPrefix=${SOCKETPATH} --config ${CONF} $DAEMON_OPTS
  LimitFSIZE=infinity
  LimitCPU=infinity
  LimitAS=infinity
  LimitNOFILE=64000
  LimitNPROC=64000
  .............

Save the file and exit it by typing Ctrl + x.

After making changes to the configuration file, run systemctl daemon-reload to reload units and restart the MongoDB service and check its status as follows.

  $ sudo systemctl daemon-reload
  $ sudo systemctl restart mongodb
  $ sudo systemctl status mongodb
  output:
  ● mongodb.service - An object/document-oriented database
     Loaded: loaded (/lib/systemd/system/mongodb.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2018-08-06 16:08:03 UTC; 20s ago
       Docs: man:mongod(1)
   Main PID: 15194 (mongod)
      Tasks: 23 (limit: 1112)
     CGroup: /system.slice/mongodb.service
             └─15194 /usr/bin/mongod --auth --unixSocketPrefix=/run/mongodb --config /etc/mongodb.con

  Aug 06 16:08:03 li34-72 systemd[1]: Stopped An object/document-oriented database.
  Aug 06 16:08:03 li34-72 systemd[1]: Started An object/document-oriented database.

Now when we try to connect to mongodb, we must authenticate ourself as a MongoDB user.

$ sudo mongo -u "root" -p --authenticationDatabase "admin"

Read Also:

Thanks for reading the article and please leave your comments below.

Ahmed Abdalhamid 1:39 am

About Ahmed Abdalhamid

Technical Support Engineer experienced in Linux servers administration of production environments. Exploring DevOps culture and tools. Interested in containerization and open source monitoring tools.

Author Archive Page

Have anything to say?

Your email address will not be published. Required fields are marked *

All comments are subject to moderation.