Install MongoDB on Ubuntu

MongoDb will soon be the de-facto data and document storage engine. Spring Java, PHP and JavaScript savvy developers are MongoDb’s biggest fan thanks to the productivity boost delivered by Mongo’s clever ground-breaking design.

Those that love SQL hate Mongo – goes the rule of thumb. Either way Mongo is here to stay so use this resource to install, lock-down, backup and access the Mongo database through

  • the BASH shell or Mongo’s cool command line interface (CLI)
  • the simple Java API using a MongoDb Java Driver
  • the Spring Data API which removes the ORM impedance mismatch
  • the now ubiquitous RESTful web service integration
  • a Web interface similar to the popular PHP MyAdmin toolset

Once installed, the MongoDb will sit atop Ubuntu‘s 16.04 Server running locally or within Amazon’s EC2 containers.

Why can’t I just run apt-get install mongodb?

Do not run apt-get install mongodb because you will get old expired versions. MongoDb is not natively bundled into Ubuntu‘s core so you must first locate its package distribution.

Double check with command sudo apt-cache search mongodb

Nothing containing mongodb will result. We will get more joy in Step 5 when we run it again.

How to install MongoDB 3.2 on Ubuntu 16.04

Follow these steps to install the Mongo NOSQL document oriented storage engine on the Ubuntu 16.04 server operating system.

  1. Create one line file with a URL for the Mongo distro.
  2. Fetch the key to the MongoDb package distributions.
  3. Run the Ubuntu aptitude cache update command.
  4. Check that the MongoDb Distribution is now available.
  5. Use apt-get to install the MongoDb last stable release.
  6. Create and Copy two (2) mongodb.service files
  7. Run Mongo as a Linux Service with Automatic Boot-Up

1. Create One Line File with Mongo Distro Url

We must create a file to contain these exact contents and place it in /etc/apt/sources.list.d/mongodb-org-3.2.list
and as it is a one-liner we simply echo the line to create the file.

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

Check all is as it should be with a cat /etc/apt/sources.list.d/mongodb-org-3.2.list which lists the one line file.

2. Run the Mongo Distro Key Fetch Command

Run the below MongoDb key registration command.

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

sudo apt-key adv –keyserver hkp://keyserver.ubuntu.com:80 –recv EA312927

This command should produce output similar to the below.

Executing: /tmp/tmp.zL8uumv7bk/gpg.1.sh --keyserver
hkp://keyserver.ubuntu.com:80
--recv
EA312927
gpg: requesting key EA312927 from hkp server keyserver.ubuntu.com
gpg: key EA312927: public key "MongoDB 3.2 Release Signing Key " imported
gpg: Total number processed: 1
gpg:               imported: 1  (RSA: 1)

3. Run the Ubuntu Aptitude Update

Now we run an aptitude command to update our cache with pointers to the last stable release of the MongoDb Ubuntu package.

sudo apt-get update

Again, for your peace of mind, you can expect lines similar to below.

Hit:1 http://eu-west-1.ec2.archive.ubuntu.com/ubuntu xenial InRelease
Get:2 http://eu-west-1.ec2.archive.ubuntu.com/ubuntu xenial-updates InRelease [102 kB]
Get:3 http://eu-west-1.ec2.archive.ubuntu.com/ubuntu xenial-backports InRelease [102 kB]
Ign:4 http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist InRelease
Get:5 http://security.ubuntu.com/ubuntu xenial-security InRelease [102 kB]
Get:6 http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist Release [2,040 B]
Get:7 http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist Release.gpg [490 B]
Get:8 http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist/10gen amd64 Packages [29.8 kB]
Fetched 339 kB in 0s (437 kB/s)
Reading package lists... Done
W: http://downloads-distro.mongodb.org/repo/ubuntu-upstart/dists/dist/Release.gpg: Signature by key 492EAFE8CD016A07919F1D2B9ECBEC467F0CEB10 uses weak digest algorithm (SHA1)

Note the references to Amazon’s eu-west-1 location in Ireland, and the references to Ubuntu’s 16.04 Xenial release.

4. Check that the MongoDb Distro is Available

In the introduction, no joy came of running sudo apt-cache search mongodb.

But that was then – and this is now. Running it produces healthier returns containing mongodb-10gen and mongodb-org entries.

mongodb-10gen - An object/document-oriented database
mongodb-org - MongoDB open source document-oriented database system (metapackage)
mongodb-org-mongos - MongoDB sharded cluster query router
mongodb-org-server - MongoDB database server
mongodb-org-shell - MongoDB shell client
mongodb-org-tools - MongoDB tools

5. Use apt-get to Install Mongo

We are now ready to install the Mongo database.

sudo apt-get install -y mongodb-org

This command will install the MongoDb Core, its RESTful web services, the Mongo Shell (command line interface) and Mongo Middleware Tools like dump, restore, import and export.

To verify the Mongodb install issue the command below.

mongod --version

The reply should give the database version, the git version and the ssl version.

db version v3.2.12
git version: ef3e1bc78e997f0d9f22f45aeb1d8e3b6ac14a14
OpenSSL version: OpenSSL 1.0.2g  1 Mar 2016
allocator: tcmalloc
modules: none
build environment:
    distmod: ubuntu1604
    distarch: x86_64
    target_arch: x86_64

6. Configuring and Running MongoDb

Failed to unlink socket file

Do not type in mongod or sudo service mongod start Because mongo will start up as root and not its own user. Use cat /etc/passwd to check that the mongodb user exists. If you start mongodb as root - the next time you start it properly the failure below will pop up in the logs tail -f /var/log/mongodb/mongod.log because the mongodb user now cannot write to the below file. Failed to unlink socket file /tmp/mongodb-27017.sock errno:1 Operation not permitted You can fix the above error by deleting /tmp/mongodb-27017.sock or changing its ownership with sudo chown mongodb:mongodb /tmp/mongodb-27017.sock

6(a) Running Mongo For the Impatient

If you are impatient that start mongo like this.

mongod  --config /path/to-xxxxxx/mongodb.conf

But you’ll need to either specify the location of the mongodb configuration file or you can specify the options on the command line itself.

Lookup the MongoDb documentation for the long list of mongod run command options.

6(b) The MongoDb Configuration File

For a standard configuration create a file /etc/mongod.conf with the below contents.


# | ## ####################################################### ## |
# | -- ------------------------------------------------------- -- |
# | -- [mongo] configuration by build-business-websites.co.uk  -- |
# | -- ------------------------------------------------------- -- |
# | ## ####################################################### ## |

# --- ------------------------------------------------------------------------- --- #
# --- Warning - Initially a similarly named file will exist in the /etc folder. --- #
# --- ------------------------------------------------------------------------- --- #

# --- ------------------------------------------------------------- --- #
# --- The /data/db location is searched for if "dbpath" is not set. --- #
# --- ------------------------------------------------------------- --- #
dbpath=/var/lib/mongodb

# --- ------------------------------------------------ --- #
# --- This is where the main mongodb log file resides. --- #
# --- $ tail -f /var/log/mongodb/mongod.log            --- #
# --- ------------------------------------------------ --- #
logpath=/var/log/mongodb/mongod.log
logappend=true

# --- ---------------------------------------------------- --- #
# --- MongoDb daemons will attach and listen to this port. --- #
# --- ---------------------------------------------------- --- #
port = 27017

# --- -------------------------------------------------------------- --- #
# --- Comma separated IP Addresses MongoDb accepts connections from. --- #
# --- -------------------------------------------------------------- --- #
bind_ip = 0.0.0.0

# --- -------------------------------------------------- --- #
# --- You could use noauth = true for no authentication. --- #
# --- -------------------------------------------------- --- #
auth = true

# --- --------------------------------------------- --- #
# --- Make the Mongo Database log output [verbose]. --- #
# --- --------------------------------------------- --- #
verbose = true

# --- ------------------------------------------------------ --- #
# Enable HTTP on port 28017 for service availability checks. --- #
# --- ------------------------------------------------------ --- #
httpinterface = true

7. Run MongoDb as a Linux Service

If you want mongodb to run as a service so that restarting your machine wakes MongoDb up automatically you need to specifiy the run options.

To do this you must add the below lines into a file named mongodb.service and copy it to 2 locations.

[Unit]
Description=High-performance, schema-free document-oriented database
After=network.target
Documentation=https://docs.mongodb.org/manual

[Service]
User=mongodb
Group=mongodb
ExecStart=/usr/bin/mongod --verbose --config /etc/mongod.conf

[Install]
WantedBy=multi-user.target

Copy the file to two locations with the commands

sudo cp xtc.lib.systemd.system.mongodb.service /lib/systemd/system/mongodb.service
sudo cp xtc.etc.systemd.system.mongodb.service /etc/systemd/system/mongodb.service

The content of the file tells Linux to run it with the mongodb user and it also specifies the command line options (in our case --verbose and --config /etc/mongod.conf). You can change --verbose to --quiet.

Now you can register MongoDb as a service. The enable command tells the system shepherd to start up Mongo alongside the other flock of services during boot time.

sudo systemctl enable mongodb

This gives MongoDb “service” status. The system will automatically start it up during boot time and also track and monitor it for you.

To manually manage mongo – use these commands to start stop and check the status of mongodb.

sudo systemctl start mongodb
sudo systemctl status mongodb
sudo systemctl stop mongodb

The status command should issue text that looks like this.

mongodb.service – High-performance, schema-free document-oriented database
Loaded: loaded (/etc/systemd/system/mongodb.service; disabled; vendor preset: Active: active (running) since Wed 2016-12-21 00:06:10 UTC; 11s ago
Docs: https://docs.mongodb.org/manual
Main PID: 11107 (mongod)
Tasks: 10
Memory: 63.0M
CPU: 60ms
CGroup: /system.slice/mongodb.service
└─11107 /usr/bin/mongod –quiet –config /etc/mongod.conf

You’ve got MongoDb up and running. Well done – it’s now lights out and away you go.

Leave a Reply

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