Skip to content

Enable TLS for MongoDB

Severity: highApplies to: MongoDB 6.x / 7.x / 8.x
The fix/etc/mongod.conf
net:
tls:
mode: requireTLS
certificateKeyFile: /etc/ssl/mongodb/server.pem
CAFile: /etc/ssl/mongodb/ca.pem
Terminal window
sudo systemctl restart mongod

Without TLS, every document you read, every document you write and the authentication exchange itself cross the network in cleartext. MongoDB’s SCRAM authentication resists replay of the stored credential, but it does nothing for the data — and the data is the entire point of a database.

The four modes, and the one that catches people

Section titled “The four modes, and the one that catches people”
Mode Accepts plaintext Accepts TLS
disabled yes no
allowTLS yes yes
preferTLS yes yes
requireTLS no yes

allowTLS and preferTLS both still accept unencrypted connections. The difference between them is only what the server prefers for internal replication traffic — neither turns anything away.

This is the same trap as Postgres and MySQL, with an extra edge: preferTLS reads like it’s doing something protective, and it is a popular half-step. A server on preferTLS will report TLS working, show encrypted connections in your testing, and quietly accept the one legacy client still connecting in the clear.

requireTLS is the only mode that requires anything.

MongoDB wants the certificate and its private key concatenated into a single PEM, which is unusual enough to be a common first stumble:

Terminal window
cat server.crt server.key > /etc/ssl/mongodb/server.pem
sudo chown mongodb:mongodb /etc/ssl/mongodb/server.pem
sudo chmod 600 /etc/ssl/mongodb/server.pem

certificateKeyFile points at that combined file, not at a cert. If MongoDB refuses to start with a TLS error, this is the first thing to check.

A server requiring TLS stops eavesdropping. Only the client decides whether it verifies which server it reached:

mongodb://app:secret@db.internal:27017/appdb?authSource=admin&tls=true&tlsCAFile=/etc/ssl/ca.pem

tls=true encrypts and validates against the CA by default — MongoDB drivers verify certificates unless you tell them not to. The options that turn that off (tlsAllowInvalidCertificates, tlsAllowInvalidHostnames) exist for self-signed certificates and are frequently pasted in to “fix” a connection error. Each one gives up exactly the protection you enabled TLS for.

If a driver only connects with tlsAllowInvalidCertificates=true, the certificate is wrong. Fix the certificate.