Security and operations

Secure the database boundary

Require authentication, narrow network access, encrypt connections, separate users, and rotate credentials without exposing an open mongod.

9 minute lesson

~~~

A MongoDB server should not be an anonymous public endpoint. That sentence sounds obvious, yet exposed unauthenticated MongoDB instances have fueled years of automated data theft: scanners find the open port, dump the data, replace it with a ransom note. Every one of those incidents started with default settings on a public address.

The boundary has four layers, and you want all of them.

Authentication. A fresh self-managed mongod does not require login. Enable it in the config file:

# /etc/mongod.conf
security:
  authorization: enabled
net:
  bindIp: 127.0.0.1

Create the administrator first, then a separate, narrowly privileged user for the application:

use animals
db.createUser({
  user: 'app_user',
  pwd: passwordPrompt(),
  roles: [ { role: 'readWrite', db: 'animals' } ]
})

readWrite on one database is enough for a typical application. The runtime account should not be able to create users, drop other databases, or reconfigure the server — that is what your separate admin account is for, used by humans, rarely.

Network. bindIp: 127.0.0.1 keeps the server on localhost. When the application lives on another host, bind to a private interface and firewall port 27017 to exactly the machines that need it. On Atlas the same idea is the IP Access List. 0.0.0.0/0 “temporarily” is how permanent holes are made.

Encryption. Use TLS on any connection that crosses a network, and prefer connection strings that require it (tls=true; Atlas mongodb+srv:// strings do this for you).

Credential hygiene. The URI embeds the password, so treat the whole URI as a secret: store it in a secret manager or deployment configuration, and make sure logs and error messages never print it. Verify that deliberately — trigger a failed connection and read what your logging actually captured:

node app.js 2>&1 | grep -c 's3cretPass'
# 0   ← must be zero

Rehearse rotation before you need it: create a second user, deploy with the new credentials, remove the old user. If that requires downtime, fix it now, not during an incident.

Finish by reviewing your practice environment against the official MongoDB security checklist, and close every access path you cannot justify out loud.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →