Tutorial

How to Install MongoDB on Ubuntu 16.04

Updated on October 13, 2020
English
How to Install MongoDB on Ubuntu 16.04
Not using Ubuntu 16.04?Choose a different version or distribution.
Ubuntu 16.04

Introduction

MongoDB is a free and open-source NoSQL document database used commonly in modern web applications. This tutorial will help you set up MongoDB on your server for a production application environment.

Prerequisites

To follow this tutorial, you will need:

Step 1 — Adding the MongoDB Repository

MongoDB is already included in Ubuntu package repositories, but the official MongoDB repository provides most up-to-date version and is the recommended way of installing the software. In this step, we will add this official repository to our server.

Ubuntu ensures the authenticity of software packages by verifying that they are signed with GPG keys, so we first have to import they key for the official MongoDB repository.

  1. wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -

After successfully importing the key, you will see:

Output
OK

Next, we have to add the MongoDB repository details so apt will know where to download the packages from.

Issue the following command to create a list file for MongoDB.

  1. echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list

After adding the repository details, we need to update the packages list.

  1. sudo apt-get update

Step 2 — Installing and Verifying MongoDB

Now we can install the MongoDB package itself.

  1. sudo apt-get install -y mongodb-org

This command will install several packages containing latest stable version of MongoDB along with helpful management tools for the MongoDB server.

Next, start MongoDB with systemctl.

  1. sudo systemctl start mongod

You can also use systemctl to check that the service has started properly.

  1. sudo systemctl status mongod
Output
● mongodb.service - High-performance, schema-free document-oriented database
   Loaded: loaded (/etc/systemd/system/mongodb.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2016-04-25 14:57:20 EDT; 1min 30s ago
 Main PID: 4093 (mongod)
    Tasks: 16 (limit: 512)
   Memory: 47.1M
      CPU: 1.224s
   CGroup: /system.slice/mongodb.service
           └─4093 /usr/bin/mongod --quiet --config /etc/mongod.conf

The last step is to enable automatically starting MongoDB when the system starts.

  1. sudo systemctl enable mongod

The MongoDB server is now configured and running, and you can manage the MongoDB service using the systemctl command (e.g. sudo systemctl stop mongod, sudo systemctl start mongod).

Step 3 — Adjusting the Firewall (Optional)

Assuming you have followed the initial server setup tutorial instructions to enable the firewall on your server, 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, it is a recommended and secure setting. However, if you would like to be able to connect to your MongoDB server from the internet, we have to allow the incoming connections in ufw.

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

in most cases, MongoDB should be accessed only from certain trusted locations, such as another server hosting an application. To accomplish this task, you can allow access on MongoDB’s default port while specifying the IP address of another server that will be explicitly allowed to connect.

  1. sudo ufw allow from your_other_server_ip/32 to any port 27017

You can verify the change in firewall settings with ufw.

  1. sudo ufw status

You should see traffic to 27017 port allowed in the output.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 the output.

Output
Status: active

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

More advanced firewall settings for restricting access to services are described in UFW Essentials: Common Firewall Rules and Commands.

Conclusion

You can find more in-depth instructions regarding MongoDB installation and configuration in these DigitalOcean community articles.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Mateusz Papiernik
Mateusz PapiernikSoftware Engineer, CTO @Makimo
See author profile
Category:
Tutorial

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
40 Comments
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

I get an error message that says:

Failed to start mongodb.service: Unit mongodb.service is masked.

when I run:

sudo systemctl start mongodb

If I just run:

sudo mongod

it works

With: sudo mongod, the service will be killed when you close the terminal.

I recommend to use:

sudo systemctl unmaks mongodb

Then you can start the service with:

sudo systemctl start mongodb

Thanks. Although you have a spelling error, should be:-

sudo systemctl unmask mongodb

Are you using a freshly created DigialOcean droplet with Ubuntu 16.04 selected during droplet creation?

I just followed all the steps from the tutorial once again to double check. After installing the packages, calling sudo systemctl unmask mongodb does nothing - there is nothing to unmask.

Calling sudo systemctl start mongodb shows the following error message:

Failed to start mongodb.service: Unit mongodb.service not found.

not the one you mention:

Failed to start mongodb.service: Unit mongodb.service is masked.

The only way to make systemctl to recognize the service is to create the systemd Unit file as described in the text.

Seeing the error you show, saying Unit mongodb.service is masked. suggests the system might have been upgraded from older Ubuntu version.

If that is the case, running sudo systemctl unmask mongodb should indeed help, as murwa says.

When I try to enable for system start with

sudo systemctl enable mongodb

I get

Failed to execute operation: Invalid argument

Help is much appreciated. Ben

Have you copied the contents of /etc/systemd/system/mongodb.service exactly as written? The error you show is most often caused by a syntax error in Unit file, for example if you put something before [Unit] in the first line.

Thanks you! Your guess was right! It was a syntax error at it] which was supposed to mean [Unit].

Glad it helped :)

The argument not is mongodb. Is mongod Angel

when i try add content to /etc/systemd/system/mongodb.service, it said “/etc/systemd/system/mongodb.service” is not a normal file ", and i cannot add content. Help me :(

In my case I get this error.

sudo systemctl status mongodb
● mongodb.service - High-performance, schema-free document-oriented database
   Loaded: loaded (/etc/systemd/system/mongodb.service; disabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Fri 2016-05-27 12:38:13 EDT; 4s ago
  Process: 6729 ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf (code=exited, status=100)
 Main PID: 6729 (code=exited, status=100)

May 27 12:38:13 ubuntu systemd[1]: Started High-performance, schema-free document-oriented database.
May 27 12:38:13 ubuntu systemd[1]: mongodb.service: Main process exited, code=exited, status=100/n/a
May 27 12:38:13 ubuntu systemd[1]: mongodb.service: Unit entered failed state.
May 27 12:38:13 ubuntu systemd[1]: mongodb.service: Failed with result 'exit-code'.

After uninstall with this command and re-start this tutorial I was able to start mongo.

sudo apt-get remove mongodb* --purge

Thank you so much! In my vagrant Ubuntu VM the mongo service was completely broken and with this tutorial I could not get mongod to start. After completely removing it and following the tut again it is working correctly.

I am getting the same problem. I think mongod is looking for different dbpath. I am getting path not found error when I just run mongod

Hi, How to set different path to dbdata and log file? I try set path to /home/user/folder and my server return fail.

Paul

they already have repo for xenial here

"deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse"

Thanks, we will be posting an update to this text soon.

We encountered a lot of issues related to the systemd configuration on a busy mongod - and improved a bit on it which can be found here: https://gist.github.com/hofmeister/a4706604c3b899eb0288f0442be5f6c4

Most important part is the TasksAccounting=false since that’ll default to true and limit the mongod service to 512 threads / sub processes

The errors we were seeing was :

NETWORK [initandlisten] pthread_create failed: errno:11 Resource temporarily unavailable

What was messing me up is that some docs refer to mongod.service and this one uses mongodb.service. Is the name up to the user? Can we call it anything we want, as long as it’s unique?

I tried this tutorial, getting ACTIVE as failed

mongodb.service - High-performance, schema-free document-oriented database Loaded: loaded (/etc/systemd/system/mongodb.service; disabled; vendor preset: Active: failed (running) since Fri 2016-05-13 10:33:52 IST; 1min 48s ago Main PID: 7078 (mongod) Tasks: 16 (limit: 512) CGroup: /system.slice/mongodb.service └─7078 /usr/bin/mongod --quiet --config /etc/mongod.conf

May 13 10:33:52 linux systemd[1]: Started High-performance, schema-free document lines 1-9/9 (END)

If using a volume to store data, what or where do I specify the storage path?

There is an error above;

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

should be

ExecStart=/usr/bin/mongod --quiet --config /etc/mongodb.conf

After startin mongodb I get:

Active: failed (Result: exit-code) since Die 2016-09-06 21:38:05 CEST; 22s ago Process: 20153 ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf (code=exited, status=14) Main PID: 20153 (code=exited, status=14)

Sep 06 21:38:05 machina8 systemd[1]: Started High-performance, schema-free document-oriented database. Sep 06 21:38:05 machina8 systemd[1]: mongodb.service: Main process exited, code=exited, status=14/n/a Sep 06 21:38:05 machina8 systemd[1]: mongodb.service: Unit entered failed state. Sep 06 21:38:05 machina8 systemd[1]: mongodb.service: Failed with result ‘exit-code’.

just do

sudo reboot

Thanks for starting out the tutorial with an explanation that MongoDB doesn’t yet use SystemD. This has confused me for months about why getting MongoDB running on a Ubuntu 16.04 install has been overly complex. Your three simple steps solve the problem. Thanks!

works perfect! thanks for the tutorial!

I have Ubuntu 16.04 x32 dev-machine from DO. I try to install mongodb for ubuntu following this tutorial, but I get error: The repository ‘http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.0 Release’ does not have a Release file screenshot

I get this error after: 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 and sudo apt-get update

Then I fire command: sudo apt-get install -y mongodb-org

And I get error: Unable to locate package mongodb-org

How to fix it?

I’ve successfully installed mongoDB 3 on ubuntu 14.04 32 bit, like that: https://docs.mongodb.com/v3.0/tutorial/install-mongodb-on-linux/#install-for-32-bit-linux

Met with the same problem like you and solved the problem by following this article step by step http://www.tutorialspoint.com/articles/how-to-install-mongodb-on-ubuntu-16-04

Hello, I’ve a machine Ubuntu 16.04.1 LTS

when i ran this command sudo systemctl enable mongodb

I’m getting this error Synchronizing state of mongodb.service with SysV init with /lib/systemd/systemd-sysv-install… Executing /lib/systemd/systemd-sysv-install enable mongodb Failed to execute operation: File exists

Need your help!

when after: sudo ufw allow from your_other_server_ip/32 to any port 27017 sudo ufw status I get error message that says: ERROR: Bad source address Status: inactive

Just got the service working by executing the following command:

sudo service mongodb start
sudo apt-get install -y --allow-unauthenticated mongodb-org

this works for me --allow-unauthenticated

Just a minor error in the otherwise great tutorial:

“The MongoDB server now configured and running, and you can manage the MongoDB service using the systemctl command (e.g. sudo systemctl mongodb stop, sudo systemctl mongodb start).”

The mongodb stop and mongodb start should be another way around, like:

“The MongoDB server now configured and running, and you can manage the MongoDB service using the systemctl command (e.g. sudo systemctl stop mongodb, sudo systemctl start mongodb).”

Otherwise the following error is produced:

$ sudo systemctl mongodb stop
Unknown operation mongodb.

you know that was bad right? Only open it to specific private machines or the private subnet. Opening mongo (or anything) for world access is naughty. You could also only have 22 open and tunnel in to access mongo via 127.0.0.1. This provides transport encryption and stops world-attacks, and fits in quite well with DigitalOcean deployment as it allows you to use a few SSH public keys so you can traverse tunnels remotely without too much fear of others

@mati @hazelnut The official tutorial says to create the service file at /lib/systemd/system/mongod.service (which already exists for me) whereas this tutorial says to create it at /etc/systemd/system/mongodb.service (which doesn’t exist for me). Note that besides the lib/etc difference, there’s also mongod vs mongodb. Perhaps things have changed since this tutorial was written? Just thought I’d let you know. Cheers

Edit: I just read this forum post which might be relevant:

service operates on the files in /etc/init.d and was used in conjunction with the old init system. systemctl operates on the files in /lib/systemd . If there is a file for your service in /lib/systemd it will use that first and if not it will fall back to the file in /etc/init.d

@roccajoseph thanks for posting this. There was no official tutorial regarding the systemd file when this article was written so we created our own. I’ll look into that and hopefully we’ll revise this article soon to be in line with the official MongoDB tutorial :)

@hazelnut I’ll keep you posted on this one, okay?

Hi, I really like the digitalocean one click apps - but they seem to lack a lot of documentation.

How do I know what decisions and trade-offs were made in order to make the MongoDB one click app? Do I really have to trawl all the config files to understand how it was configured?

Building on a Mongo one click app, I published something to help someone set up a Replica Set in just a few minutes.

http://undefinedbehaviour.xyz/2016/12/21/mongodb-replica-set/

I needed to run

sudo apt-get install -y mongodb

instead of

sudo apt-get install -y mongodb-org

I had to use

sudo apt-get install -y mongodb

(without “-org” suffix)

also config file in service file should be

mongodb.conf 

not “mongod.conf”

For me the first 2 steps works ok today, but I think the order of the outputs shown and the commands executed at the end of Step 2 are this way:

1 - First time you get the step to check the systemctl status mongodb

sudo systemctl status mongodb

Output:

● mongodb.service - High-performance, schema-free document-oriented database
   Loaded: loaded (/etc/systemd/system/mongodb.service; disabled; vendor preset: enabled)
   Active: inactive (dead)

2 - Enable mongodb:

sudo systemctl enable mongodb.service

Output:

● mongodb.service - High-performance, schema-free document-oriented database
   Loaded: loaded (/etc/systemd/system/mongodb.service; enabled; vendor preset: enabled)
   Active: inactive (dead)

3 - Start mongodb:

sudo systemctl start mongodb

Output:

● mongodb.service - High-performance, schema-free document-oriented database
   Loaded: loaded (/etc/systemd/system/mongodb.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2017-01-12 07:10:46 UTC; 2s ago
 Main PID: 12623 (mongod)
    Tasks: 16
   Memory: 50.4M
      CPU: 252ms
   CGroup: /system.slice/mongodb.service
           └─12623 /usr/bin/mongod --quiet --config /etc/mongod.conf

But, if you check the status of the jobs by using:

systemctl list-unit-files --type=service

I can see there still is a mongod.service disabled…

mongod.service                             disabled
mongodb.service                            enabled

Any idea if it is needed or I should remove it? What step should be changed to avoid it?

I am able to run sudo systemctl enable mongod without creating mongodb.service in 16.04! It creates /etc/systemd/system/multi-user.target.wants/mongod.service

Perhaps i missed it, but if you want to be able to connect to this mongo instance externally, you’ll need to add your ip address (the same one you added in the ufw settings) to the mongodb configuration file (/etc/mongod.conf) like so:

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1,YOUR_EXTERAL_IP

<3 Thank you! I was going insane trying to figure this out.

I’m trying to install at least mongodb 3.2 on ubuntu 16.10 because I really need the $sample command.

I can’t seem to get this working. Any help would be appreciated.

Oh man, you should have mentioned that we should change “bind_ip” in /etc/mongod.conf to the other server’s ip address as well. The ufw config is useless without this. I banged my head against the wall but ended up being able to search it out in another thread.

Hi to all!

I am experiencing this error at the end of step 2:

Apr 17 13:14:40 ubuntu-512mb-ams2-01 systemd[1]: Started High-performance, schema-free document-oriented database. Apr 17 13:14:40 ubuntu-512mb-ams2-01 systemd[2359]: mongodb.service: Failed at step USER spawning /usr/bin/mongod: No such process Apr 17 13:14:40 ubuntu-512mb-ams2-01 systemd[1]: mongodb.service: Main process exited, code=exited, status=217/USER Apr 17 13:14:40 ubuntu-512mb-ams2-01 systemd[1]: mongodb.service: Unit entered failed state. Apr 17 13:14:40 ubuntu-512mb-ams2-01 systemd[1]: mongodb.service: Failed with result ‘exit-code’.

Has anyone also encountered this and maybe found a solution for it? Thanks!

Hello, thanks for this helpful article.

I got mongo to work the first time I followed this tutorial. However, today is the day after and I can’t seem to make it work anymore. Now I get the below:

root@texasbros:~# sudo systemctl start mongodb
root@texasbros:~# sudo systemctl status mongodb
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 Sun 2017-04-23 14:27:07 UTC; 11s ago
  Process: 16643 ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf (code=exited, status=14)
 Main PID: 16643 (code=exited, status=14)

Apr 23 14:27:07 texasbros systemd[1]: Started High-performance, schema-free document-oriented database.
Apr 23 14:27:07 texasbros systemd[1]: mongodb.service: Main process exited, code=exited, status=14/n/a
Apr 23 14:27:07 texasbros systemd[1]: mongodb.service: Unit entered failed state.
Apr 23 14:27:07 texasbros systemd[1]: mongodb.service: Failed with result 'exit-code'.

Great article. One note though: there’s no need to create a unit file (/etc/systemd/system/mongodb.service) for MongoDB. It’s easier to simply enable the unit provided by package (Note that below the correct is mongod, not to be confused with mongodb)

sudo systemctl enable mongod

I’m receiving an error stating that it cannot find the configuration file.

systemd[1]: Started High-performance, schema-free document-oriented database. mongod[2205]: Error reading config file: No such file or directory mongod[2205]: try ‘/usr/bin/mongod --help’ for more information ystemd[1]: mongodb.service: Main process exited, code=exited, status=2/INVALIDARGUMENT systemd[1]: mongodb.service: Unit entered failed state. systemd[1]: mongodb.service: Failed with result ‘exit-code’. systemd[1]: Stopped High-performance, schema-free document-oriented database.

However when I run the following command the file exists.

sudo nano /etc/systemd/system/mongodb.service

Is there another config file I should be creating? If so I did not see it in the tutorial.

E: Unable to locate package mongodb-org

sudo systemctl status mongodb

should be

sudo systemctl status mongod

Since you start the service with

sudo systemctl start mongod

Shouldn’t you check the status with

sudo systemctl status mongod

Bogus article. Didn’t even work.

● mongodb.service Loaded: not-found (Reason: No such file or directory) Active: inactive (dead) root@ITHERAEL:~# sudo systemctl enable mongodb Failed to execute operation: No such file or directory

I get this message : ```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 Tue 2017-12-05 13:30:01 UTC; 38s ago Main PID: 6387 (code=exited, status=48)

Dec 05 13:30:01 ubuntu-512mb-fra1-01 systemd[1]: Started High-performance, schema-free document-oriented database. Dec 05 13:30:01 ubuntu-512mb-fra1-01 systemd[1]: mongodb.service: Main process exited, code=exited, status=48/n/a Dec 05 13:30:01 ubuntu-512mb-fra1-01 systemd[1]: mongodb.service: Unit entered failed state. Dec 05 13:30:01 ubuntu-512mb-fra1-01 systemd[1]: mongodb.service: Failed with result ‘exit-code’.```

when i run sudo systemctl status mongodb

I have uninstall and reinstall mongo db and followed the steps twice but can’t seem to find a way to solve it. Please does anyone know what to do?

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.