1. Import they key for the official MongoDB repository
$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927
After successfully importing the key, you will see:
gpg: Total number processed: 1 gpg: imported: 1 (RSA: 1)
2. Issue the following command to create a list file for MongoDB
$ 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
3. Update the packages list.
$ sudo apt-get update
4. Install MongoDB
$ sudo apt-get install -y mongodb-org
5. Create a unit file to manage the MongoDB service.
Create a configuration file named mongodb.service in the /etc/systemd/system directory:
$ sudo nano /etc/systemd/system/mongodb.service
Paste in the following contents:
[Unit] Description=High-performance, schema-free document-oriented database After=network.target [Service] User=mongodb ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf [Install] WantedBy=multi-user.target
Ctrl+x to save and ‘Y’ to exit
This file has a simple structure:
The Unit section contains the overview (e.g. a human-readable description for MongoDB service) as well as dependencies that must be satisfied before the service is started. In our case, MongoDB depends on networking already being available, hence network.target here.
The Service section how the service should be started. The User directive specifies that the server will be run under the mongodb user, and the ExecStart directive defines the startup command for MongoDB server.
The last section, Install, tells systemd when the service should be automatically started. The multi-user.target is a standard system startup sequence, which means the server will be automatically started during boot.
6. Start the newly created service with systemctl
$ sudo systemctl start mongodb
you will see:
● mongodb.service Loaded: loaded (/etc/systemd/system/mongodb.service; disabled; vendor preset: Active: active (running) since Wed 2017-08-30 17:33:53 UTC; 3s ago Main PID: 3110 (mongod) Tasks: 19 Memory: 52.8M CPU: 78ms CGroup: /system.slice/mongodb.service └─3110 /usr/bin/mongod --quiet --config /etc/mongod.conf Aug 30 17:33:53 vagrant systemd: Started mongodb.service. lines 1-11/11 (END)
7. Automatically start MongoDB when the system starts
$ sudo systemctl enable mongodb
The MongoDB server is now configured and running, and you can start/stop the MongoDB service using the systemctl command:
$ sudo systemctl mongodb stop
or to stop:
$ sudo systemctl mongodb start
More on adjusting the optional server firewall if you would like to be able to connect to your MongoDB server from the internet can be found at (the default port is 27017):