Enable Security on Mongo DB With Remote Access
Adam C. |

Mongo has a very good tutorial for us to install MongoDB Community Verison at:  https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/ (Note: the link is for Ubuntu. Just look for other systems via the page, and by the time of this writing, MongoDB does not officially support Ubuntu 22.04 yet)

Photo by tripleMdesignz on Unsplash

By default, MongoDB has no enabled access control, so there is no default user or password. But you can only access it via Localhost. Here is my default setup after installation. 

Create Admin User: 

>mongosh // run from command line to login mongo shell

db.createUser( { 
	user: "admin", pwd: "STRONGPASS", 
	roles: [ { role: "root", db: "admin" } ] 
} )

Create Application User

>mongosh // run from command line to login mongo shell

db.createUser({ 
	user: "powerUser" , pwd: "STRONGPASS", 
	roles: ["userAdminAnyDatabase", "dbAdminAnyDatabase", "readWriteAnyDatabase"]
})

Enable authentication

net:
  port: 27017
  bindIp: 127.0.0.1,BOXIP
  
security:
  authorization: 'enabled'

Edit mongo.config (by default under /etc) by uncommenting ‘security’ and adding “authorization: 'enabled'”.  To allow remote access, bind the box IP (ex:  your VPS IP).

IMPORTANT:

  1. mongo.config is a yml file, so the formatting matters. Use two spaces, not three, not one, not tab.
  2. the BOXIP is your server's IP, if you are using Digital Ocean, this is a Reserved IP, which you can use to access your box, but it's NOT the one you should bind to. Otherwise, you cannot restart your Mongo with no meaningful error message like below, which may be the reason you come to this post.

● mongod.service - MongoDB Database Server

     Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)

     Active: failed (Result: exit-code) since Wed 2022-07-06 15:04:47 EDT; 1s ago

       Docs: https://docs.mongodb.org/manual

    Process: 52747 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=exited, status=48)

   Main PID: 52747 (code=exited, status=48)


 

Jul 06 15:04:47 ubuntu-s-2vcpu-4gb-intel-sfo3-01 systemd[1]: Started MongoDB Database Server.

Jul 06 15:04:47 ubuntu-s-2vcpu-4gb-intel-sfo3-01 systemd[1]: mongod.service: Main process exited, code=exited, status=48/n/a

Jul 06 15:04:47 ubuntu-s-2vcpu-4gb-intel-sfo3-01 systemd[1]: mongod.service: Failed with result 'exit-code'.