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.
sudo apt update
sudo apt install -y gnupg curl ca-certificatesMongoDB 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:
curl -fsSL https://www.mongodb.org/static/pgp/server-<version>.asc \
| sudo gpg -o /usr/share/keyrings/mongodb-server-<version>.gpg --dearmorecho "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>.listThen refresh the package lists.
sudo apt updateNote: 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
sudo apt install -y mongodb-orgThis installs the mongod server, the shell and the command line tools. Confirm the binary is present:
mongod --versionTip: 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
sudo systemctl enable --now mongod
systemctl status mongod --no-pagerYou should see active (running). The default /etc/mongod.conf already binds to localhost, so confirm that:
ss -tlnp | grep 27017The 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:
sudo journalctl -u mongod -n 50 --no-pagerCreate 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.
mongoshCreate a user with the root role in the admin database. passwordPrompt keeps the password out of your shell history.
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:
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.
sudo cp /etc/mongod.conf /etc/mongod.conf.bak
sudo nano /etc/mongod.confAdd the security block at the end of the file:
security:
authorization: enabledWarning: 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:
sudo systemctl restart mongod
systemctl status mongod --no-pagerLock 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.
net:
port: 27017
bindIp: 127.0.0.1,203.0.113.10Restart after the change:
sudo systemctl restart mongodNow restrict the port at the firewall. Allow SSH first so you do not lock yourself out.
sudo ufw allow OpenSSH
sudo ufw allow from 203.0.113.10 to any port 27017 proto tcp
sudo ufw enable
sudo ufw status verboseThe 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.
mongosh --host 127.0.0.1 --port 27017 -u mongoAdmin -p --authenticationDatabase adminInside the shell, confirm you are authenticated:
db.runCommand({ connectionStatus: 1 })The authenticatedUsers array should list mongoAdmin against the admin database. Now test that anonymous access is refused:
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
mongoshconnects with no credentials —authorization: enabledis missing, indented under the wrong parent, or the service was not restarted. Compare against/etc/mongod.conf.bakand runsudo systemctl restart mongod.Authentication failedwith correct credentials — the user lives in a database you did not specify. Add--authenticationDatabase adminfor admin users, or the database name you created the user in.mongodwill not start after editing the config — usually a YAML syntax problem or a tab character. Runsudo journalctl -u mongod -n 50 --no-pager; the parser reports the offending line.- Remote clients time out — either
bindIpstill lists only127.0.0.1, or UFW has no rule for the source address. Check withss -tlnp | grep 27017andsudo ufw status numbered. apt updatefails 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
- Harden the rest of the server with UFW.
- Running MySQL or MariaDB alongside MongoDB? Follow install and secure MariaDB or MySQL.
- Add a cache layer with install and secure Redis.
- Put the application in front of the database with install Nginx.
