MongoDB is an open-source database primarily used in modern web applications.
MongoDB Repository #
MongoDB is available in Ubuntu packages, but the official MongoDB repository offers the latest version.
We will add the key for the official MongoDB repository.
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv D68FA50FEA312927
Use the full (long) key ID. For the short ID EA312927 the keyserver also returns a forged key from someone else, which apt would add to its trusted keys.
Next, we will add the details of the repository.
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
Subsequently, we need to update the package list.
sudo apt-get update
Installation of MongoDB #
To install the package, follow these steps:
sudo apt-get install -y mongodb-org
The command will download and install several packages, including MongoDB and other tools.
After that, you can start MongoDB.
sudo systemctl start mongod
Now MongoDB is running, and you can verify this using:
sudo systemctl status mongod
But if you restart the server, you will need to manually start MongoDB again.
To enable MongoDB to start automatically at boot, you can use:
sudo systemctl enable mongod
Firewall Configuration #
If you have a configured firewall, most likely, you will need to adjust the firewall settings.
In cases where your application is on a different server than MongoDB, you will need to allow connections from that server.
The default port for MongoDB is 27017.
After installation MongoDB listens only on 127.0.0.1. To let the other server connect, add this server's IP address to bindIp in /etc/mongod.conf (for example bindIp: 127.0.0.1,this-server-ip) and restart it with sudo systemctl restart mongod.
By default MongoDB requires no login. Before you expose it to the network, create an administrator user and enable authentication (security: and authorization: enabled in /etc/mongod.conf).
For ufw
sudo ufw allow from ip-server/32 to any port 27017
For iptables
sudo iptables -A INPUT -s ip-server -p tcp --destination-port 27017 -m state --state NEW,ESTABLISHED -j ACCEPT
sudo iptables -A OUTPUT -d ip-server -p tcp --source-port 27017 -m state --state ESTABLISHED -j ACCEPT
Done.