Install and configure MongoDB 8.0 with authentication and SSL encryption

Beginner 25 min Apr 03, 2026 16 views
Ubuntu 24.04 Ubuntu 22.04 Debian 12 AlmaLinux 9 Rocky Linux 9 Fedora 41

Set up MongoDB 8.0 from official repositories with authentication enabled and SSL/TLS encryption. Configure admin users, implement security hardening, and establish monitoring for production deployments.

Prerequisites

  • Root or sudo access
  • 2GB RAM minimum
  • 10GB disk space
  • Open ports 27017

What this solves

MongoDB 8.0 provides a robust NoSQL database solution for applications requiring flexible document storage and high performance. This tutorial covers installation from official repositories, enabling authentication with admin users, implementing SSL/TLS encryption, and configuring essential security hardening for production environments.

Step-by-step installation

Update system packages

Start by updating your package manager to ensure you get the latest security patches and dependencies.

sudo apt update && sudo apt upgrade -y
sudo apt install -y wget curl gnupg2 software-properties-common apt-transport-https ca-certificates lsb-release
sudo dnf update -y
sudo dnf install -y wget curl gnupg2 yum-utils

Add MongoDB official repository

Import the MongoDB GPG key and add the official repository to ensure you get authentic MongoDB 8.0 packages with security updates.

curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg --dearmor
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu $(lsb_release -cs)/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
sudo apt update
sudo rpm --import https://www.mongodb.org/static/pgp/server-8.0.asc
sudo tee /etc/yum.repos.d/mongodb-org-8.0.repo << 'EOF'
[mongodb-org-8.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/9/mongodb-org/8.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-8.0.asc
EOF

Install MongoDB 8.0

Install the MongoDB server, client tools, and additional utilities from the official repository.

sudo apt install -y mongodb-org
sudo systemctl daemon-reload
sudo dnf install -y mongodb-org
sudo systemctl daemon-reload

Create MongoDB data directories

Set up the data directory with correct ownership and permissions for the MongoDB user.

sudo mkdir -p /var/lib/mongodb /var/log/mongodb
sudo chown -R mongod:mongod /var/lib/mongodb /var/log/mongodb
sudo chmod 750 /var/lib/mongodb /var/log/mongodb
Note: MongoDB runs as the mongod user for security. Directory permissions 750 allow the owner full access while restricting others.

Configure basic MongoDB settings

Create the initial configuration file with basic settings before enabling authentication.

storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log
  logRotate: rename

net:
  port: 27017
  bindIp: 127.0.0.1

processManagement:
  timeZoneInfo: /usr/share/zoneinfo
  fork: true
  pidFilePath: /var/run/mongodb/mongod.pid

setParameter:
  authenticationMechanisms: SCRAM-SHA-256

Start MongoDB service

Enable and start MongoDB to begin the configuration process.

sudo systemctl enable mongod
sudo systemctl start mongod
sudo systemctl status mongod

Create administrative user

Connect to MongoDB and create an admin user with full privileges before enabling authentication.

mongosh --port 27017
use admin
db.createUser({
  user: "admin",
  pwd: passwordPrompt(),
  roles: ["root"]
})
db.createUser({
  user: "dbadmin",
  pwd: passwordPrompt(),
  roles: [
    "userAdminAnyDatabase",
    "dbAdminAnyDatabase",
    "readWriteAnyDatabase"
  ]
})
exit
Note: Use passwordPrompt() to securely enter passwords. Choose strong passwords with mixed case, numbers, and symbols.

Generate SSL certificates

Create SSL certificates for encrypted connections. In production, use certificates from a trusted CA.

sudo mkdir -p /etc/mongodb/ssl
sudo openssl req -new -x509 -days 365 -nodes -out /etc/mongodb/ssl/mongodb-cert.crt -keyout /etc/mongodb/ssl/mongodb-cert.key -subj "/C=US/ST=State/L=City/O=Organization/OU=IT/CN=example.com"
sudo cat /etc/mongodb/ssl/mongodb-cert.key /etc/mongodb/ssl/mongodb-cert.crt > /etc/mongodb/ssl/mongodb.pem
sudo chown -R mongod:mongod /etc/mongodb/ssl
sudo chmod 600 /etc/mongodb/ssl/*
Warning: Self-signed certificates are suitable for testing only. For production, obtain certificates from a trusted Certificate Authority.

Enable authentication and SSL

Update the configuration to enable authentication and SSL encryption for secure connections.

storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log
  logRotate: rename

net:
  port: 27017
  bindIp: 127.0.0.1,203.0.113.10
  tls:
    mode: requireTLS
    certificateKeyFile: /etc/mongodb/ssl/mongodb.pem
    allowConnectionsWithoutCertificates: true

processManagement:
  timeZoneInfo: /usr/share/zoneinfo
  fork: true
  pidFilePath: /var/run/mongodb/mongod.pid

security:
  authorization: enabled
  
setParameter:
  authenticationMechanisms: SCRAM-SHA-256
  tlsLogVersions: "TLS1_2,TLS1_3"

Configure firewall rules

Set up firewall rules to control access to MongoDB. Only allow connections from trusted networks.

sudo ufw allow from 203.0.113.0/24 to any port 27017
sudo ufw reload
sudo ufw status
sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='203.0.113.0/24' port protocol='tcp' port='27017' accept"
sudo firewall-cmd --reload
sudo firewall-cmd --list-all

Apply security hardening settings

Add additional security configurations to protect against common attacks and limit resource usage.

storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
  wiredTiger:
    engineConfig:
      cacheSizeGB: 2
      directoryForIndexes: true

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log
  logRotate: rename
  verbosity: 1

net:
  port: 27017
  bindIp: 127.0.0.1,203.0.113.10
  maxIncomingConnections: 200
  tls:
    mode: requireTLS
    certificateKeyFile: /etc/mongodb/ssl/mongodb.pem
    allowConnectionsWithoutCertificates: true

processManagement:
  timeZoneInfo: /usr/share/zoneinfo
  fork: true
  pidFilePath: /var/run/mongodb/mongod.pid

security:
  authorization: enabled
  javascriptEnabled: false
  
operationProfiling:
  slowOpThresholdMs: 200
  mode: slowOp

setParameter:
  authenticationMechanisms: SCRAM-SHA-256
  tlsLogVersions: "TLS1_2,TLS1_3"
  cursorTimeoutMillis: 600000
  failIndexKeyTooLong: false

Restart MongoDB with new configuration

Apply all configuration changes by restarting the MongoDB service.

sudo systemctl restart mongod
sudo systemctl status mongod

Configure log rotation

Set up automatic log rotation to prevent log files from consuming excessive disk space.

/var/log/mongodb/*.log {
    daily
    missingok
    rotate 52
    compress
    notifempty
    create 640 mongod mongod
    sharedscripts
    postrotate
        /bin/kill -SIGUSR1 cat /var/run/mongodb/mongod.pid 2>/dev/null 2>/dev/null || true
    endscript
}

Create database backup script

Set up automated backups with compression and retention policies for data protection.

#!/bin/bash

BACKUP_DIR="/opt/mongodb-backups"
DATE=$(date +"%Y%m%d_%H%M%S")
RETENTION_DAYS=7
MONGO_USER="dbadmin"
MONGO_PASSWORD="your_secure_password"

mkdir -p "$BACKUP_DIR"

Create backup

mongodump --host localhost:27017 --tls --tlsAllowInvalidCertificates \ --username "$MONGO_USER" --password="$MONGO_PASSWORD" \ --authenticationDatabase admin \ --out "$BACKUP_DIR/backup_$DATE"

Compress backup

tar -czf "$BACKUP_DIR/backup_$DATE.tar.gz" -C "$BACKUP_DIR" "backup_$DATE" rm -rf "$BACKUP_DIR/backup_$DATE"

Clean old backups

find "$BACKUP_DIR" -name "backup_*.tar.gz" -mtime +$RETENTION_DAYS -delete echo "Backup completed: backup_$DATE.tar.gz"
sudo chmod 750 /usr/local/bin/mongodb-backup.sh
sudo chown root:mongod /usr/local/bin/mongodb-backup.sh

Set up monitoring with systemd

Create a monitoring service to track MongoDB health and performance metrics.

[Unit]
Description=MongoDB Health Monitor
After=mongod.service
Requires=mongod.service

[Service]
Type=simple
User=mongod
ExecStart=/usr/local/bin/mongodb-monitor.sh
Restart=always
RestartSec=60

[Install]
WantedBy=multi-user.target
#!/bin/bash

LOG_FILE="/var/log/mongodb/monitor.log"
MONGO_USER="dbadmin"
MONGO_PASSWORD="your_secure_password"

while true; do
    TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
    
    # Check MongoDB status
    STATUS=$(mongosh --host localhost:27017 --tls --tlsAllowInvalidCertificates \
      --username "$MONGO_USER" --password="$MONGO_PASSWORD" \
      --authenticationDatabase admin --quiet --eval "db.runCommand('ping').ok" 2>/dev/null)
    
    if [ "$STATUS" = "1" ]; then
        echo "[$TIMESTAMP] MongoDB: OK" >> "$LOG_FILE"
    else
        echo "[$TIMESTAMP] MongoDB: ERROR - Service not responding" >> "$LOG_FILE"
    fi
    
    sleep 300  # Check every 5 minutes
done
sudo chmod 750 /usr/local/bin/mongodb-monitor.sh
sudo chown mongod:mongod /usr/local/bin/mongodb-monitor.sh
sudo systemctl daemon-reload
sudo systemctl enable mongodb-monitor
sudo systemctl start mongodb-monitor

Verify your setup

Test the MongoDB installation, authentication, and SSL encryption to ensure everything works correctly.

sudo systemctl status mongod
sudo systemctl status mongodb-monitor
mongosh --host localhost:27017 --tls --tlsAllowInvalidCertificates --username admin --password --authenticationDatabase admin
db.runCommand("connectionStatus")
db.adminCommand("listCollections")
use test
db.testCollection.insertOne({message: "Hello MongoDB 8.0", timestamp: new Date()})
db.testCollection.find()
exit

For more system monitoring techniques, see our guide on Linux performance monitoring with htop.

Performance tuning

Apply these optimizations based on your server specifications and workload requirements.

mongod soft nproc 32000
mongod hard nproc 32000
mongod soft nofile 64000
mongod hard nofile 64000
echo 'vm.swappiness=1' | sudo tee -a /etc/sysctl.conf
echo 'vm.dirty_ratio=15' | sudo tee -a /etc/sysctl.conf
echo 'vm.dirty_background_ratio=5' | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

For comprehensive filesystem performance optimization, review our tutorial on optimizing Linux filesystem performance.

Common issues

SymptomCauseFix
Service fails to startConfiguration syntax errorsudo mongod --config /etc/mongod.conf --fork to test config
SSL connection refusedCertificate file permissionssudo chmod 600 /etc/mongodb/ssl/* and verify ownership
Authentication failedWrong authentication databaseUse --authenticationDatabase admin for admin users
Cannot bind to IP addressNetwork interface not availableCheck ip addr show and update bindIp in config
High memory usageDefault WiredTiger cache sizeSet cacheSizeGB to 50-80% of available RAM
Log files growing rapidlyVerbose logging enabledReduce verbosity level in systemLog section

Next steps

Automated install script

Run this to automate the entire setup

#mongodb #nosql #database #authentication #ssl #security #mongodb-8.0

Need help?

Don't want to manage this yourself?

We handle infrastructure for businesses that depend on uptime. From initial setup to ongoing operations.

Talk to an engineer