Databases

How to install MongoDB on Ubuntu and secure it

Install MongoDB on Ubuntu from the official repository, enable authentication, create an admin user, and restrict access with bindIp and UFW.

IntermediateLinux server6 min read

This guide installs MongoDB on Ubuntu 22.04 or 24.04 from MongoDB's own repository, then closes the two gaps that catch most new deployments: no authentication and a database listening on every network interface. You will create an admin user, switch on authorisation, and restrict the port with bindIp and UFW.

Before you start

  • A Linux VPS running Ubuntu 22.04 or 24.04, with root or sudo access. If you still need a sudo account, see create a sudo user.
  • SSH access to the server. What is SSH explains the basics if you are new to it.
  • Enough RAM for your working set. Read MongoDB's production notes before you size the server.
  • The IP address of any host that has to reach the database remotely. If only a local application connects, you will not need one.

Run everything below as your sudo user. You can watch the server, open a console and reinstall the OS from your VPS provider's control panel if a step goes wrong.

Warning: Do not use the mongodb package from the Ubuntu archive for a new deployment. It lags behind and is configured differently. Use MongoDB's own repository so you control the version and the config file layout.

Add the MongoDB repository

Install the tools needed to fetch and verify the repository key.

Bash
sudo apt update
sudo apt install -y gnupg curl ca-certificates

MongoDB publishes the key file and the APT list line on its own install page, and both change when a new release line ships. Open MongoDB's official "Install on Ubuntu" documentation and copy the current commands. The shape is this, with the version substituted:

Bash
curl -fsSL https://www.mongodb.org/static/pgp/server-<version>.asc \
  | sudo gpg -o /usr/share/keyrings/mongodb-server-<version>.gpg --dearmor
Bash
echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-<version>.gpg ] https://repo.mongodb.org/apt/ubuntu $(lsb_release -cs)/mongodb-org/<version> multiverse" \
  | sudo tee /etc/apt/sources.list.d/mongodb-org-<version>.list

Then refresh the package lists.

Bash
sudo apt update

Note: If apt update reports NO_PUBKEY or cannot find the mongodb-org package, the release codename in the list file does not match your Ubuntu version. Check the vendor page again rather than guessing.

Install MongoDB

Bash
sudo apt install -y mongodb-org

This installs the mongod server, the shell and the command line tools. Confirm the binary is present:

Bash
mongod --version

Tip: A routine apt upgrade can pull in a newer major version. If you want to stay on the release line you installed, hold the packages with sudo apt-mark hold mongodb-org mongodb-org-server mongodb-org-mongos mongodb-org-tools mongodb-mongosh and unhold them when you plan an upgrade.

Start the service and check the defaults

Bash
sudo systemctl enable --now mongod
systemctl status mongod --no-pager

You should see active (running). The default /etc/mongod.conf already binds to localhost, so confirm that:

Bash
ss -tlnp | grep 27017

The output should show 127.0.0.1:27017, not 0.0.0.0:27017. If it shows the wildcard address, stop and fix bindIp before going further.

Logs live in the journal:

Bash
sudo journalctl -u mongod -n 50 --no-pager

Create the admin user

Warning: Create the admin user before you enable authorisation. If you turn authentication on first, you will not be able to connect and will have to edit the config from the console to recover.

Open the shell. Authentication is still off, so no credentials are needed yet.

Bash
mongosh

Create a user with the root role in the admin database. passwordPrompt keeps the password out of your shell history.

JavaScript
use admin
db.createUser({
  user: "mongoAdmin",
  pwd: passwordPrompt(),
  roles: [ { role: "root", db: "admin" } ]
})

Type the password at the prompt. Then create a narrower user for your application instead of connecting as root:

JavaScript
db.createUser({
  user: "appuser",
  pwd: passwordPrompt(),
  roles: [ { role: "readWrite", db: "appdb" } ]
})

Leave the shell with exit.

Enable authentication

Back up the config first, then edit it.

Bash
sudo cp /etc/mongod.conf /etc/mongod.conf.bak
sudo nano /etc/mongod.conf

Add the security block at the end of the file:

YAML
security:
  authorization: enabled

Warning: The config file is YAML. Use two spaces for indentation and never tabs. A single misplaced character stops mongod from starting.

Restart the service and confirm it comes back up:

Bash
sudo systemctl restart mongod
systemctl status mongod --no-pager

Lock down the network

Keep bindIp: 127.0.0.1 if your application runs on the same server. That is the safest setting and nothing else is required.

If a remote host must connect, add that server's own IP address to the list. Use the private address, not a public one, and never 0.0.0.0.

YAML
net:
  port: 27017
  bindIp: 127.0.0.1,203.0.113.10

Restart after the change:

Bash
sudo systemctl restart mongod

Now restrict the port at the firewall. Allow SSH first so you do not lock yourself out.

Bash
sudo ufw allow OpenSSH
sudo ufw allow from 203.0.113.10 to any port 27017 proto tcp
sudo ufw enable
sudo ufw status verbose

The second rule allows a single source address. Replace it with the address of the machine that connects. See set up UFW for more detail on rule order and logging.

Warning: Never open port 27017 to the whole internet. A database port exposed to the internet is found and attacked within hours, and authentication alone is not a substitute for a firewall rule.

Check it works

Connect with the admin user. The -p flag prompts for the password.

Bash
mongosh --host 127.0.0.1 --port 27017 -u mongoAdmin -p --authenticationDatabase admin

Inside the shell, confirm you are authenticated:

JavaScript
db.runCommand({ connectionStatus: 1 })

The authenticatedUsers array should list mongoAdmin against the admin database. Now test that anonymous access is refused:

Bash
mongosh --host 127.0.0.1 --port 27017 --eval 'db.adminCommand({ listDatabases: 1 })'

You want an error such as command listDatabases requires authentication. If the command succeeds, authorisation is not active — check that the security block is indented correctly and that you restarted mongod.

Finally, if you allowed remote access, test from the allowed host with mongosh --host 203.0.113.10 --port 27017 -u appuser -p --authenticationDatabase admin, and confirm the port is closed from anywhere else.

Troubleshooting

  • mongosh connects with no credentials — authorization: enabled is missing, indented under the wrong parent, or the service was not restarted. Compare against /etc/mongod.conf.bak and run sudo systemctl restart mongod.
  • Authentication failed with correct credentials — the user lives in a database you did not specify. Add --authenticationDatabase admin for admin users, or the database name you created the user in.
  • mongod will not start after editing the config — usually a YAML syntax problem or a tab character. Run sudo journalctl -u mongod -n 50 --no-pager; the parser reports the offending line.
  • Remote clients time out — either bindIp still lists only 127.0.0.1, or UFW has no rule for the source address. Check with ss -tlnp | grep 27017 and sudo ufw status numbered.
  • apt update fails on the MongoDB repository — the key or the list file points at a release line that does not exist for your Ubuntu codename. Re-copy both lines from the vendor's install page.

Next steps

Was this guide helpful?

Still stuck?

Ask MdmHost AI for a quick answer, or open a ticket and our team will take a look. We are here 24/7.