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
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
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
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
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
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/*
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
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
| Symptom | Cause | Fix |
|---|---|---|
| Service fails to start | Configuration syntax error | sudo mongod --config /etc/mongod.conf --fork to test config |
| SSL connection refused | Certificate file permissions | sudo chmod 600 /etc/mongodb/ssl/* and verify ownership |
| Authentication failed | Wrong authentication database | Use --authenticationDatabase admin for admin users |
| Cannot bind to IP address | Network interface not available | Check ip addr show and update bindIp in config |
| High memory usage | Default WiredTiger cache size | Set cacheSizeGB to 50-80% of available RAM |
| Log files growing rapidly | Verbose logging enabled | Reduce verbosity level in systemLog section |
Next steps
Automated install script
Run this to automate the entire setup
#!/usr/bin/env bash
set -euo pipefail
# MongoDB 8.0 Installation and Configuration Script
# Production-ready with authentication and SSL/TLS encryption
# Colors for output
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly NC='\033[0m' # No Color
# Configuration variables
MONGODB_IP="${1:-127.0.0.1}"
ADMIN_USER="${2:-admin}"
ADMIN_PASSWORD="${3:-$(openssl rand -base64 32)}"
NETWORK_CIDR="${4:-127.0.0.0/8}"
usage() {
echo "Usage: $0 [MONGODB_IP] [ADMIN_USER] [ADMIN_PASSWORD] [NETWORK_CIDR]"
echo "Example: $0 192.168.1.100 dbadmin mypassword 192.168.1.0/24"
exit 1
}
log_info() {
echo -e "${GREEN}$1${NC}"
}
log_warn() {
echo -e "${YELLOW}$1${NC}"
}
log_error() {
echo -e "${RED}$1${NC}"
}
cleanup() {
log_error "Installation failed. Cleaning up..."
systemctl stop mongod 2>/dev/null || true
systemctl disable mongod 2>/dev/null || true
if [[ "$PKG_MGR" == "apt" ]]; then
apt-get remove -y mongodb-org 2>/dev/null || true
rm -f /etc/apt/sources.list.d/mongodb-org-8.0.list
rm -f /usr/share/keyrings/mongodb-server-8.0.gpg
else
dnf remove -y mongodb-org 2>/dev/null || true
rm -f /etc/yum.repos.d/mongodb-org-8.0.repo
fi
rm -rf /etc/mongodb/ssl
exit 1
}
trap cleanup ERR
check_prerequisites() {
log_info "[1/10] Checking prerequisites..."
if [[ $EUID -ne 0 ]]; then
log_error "This script must be run as root or with sudo"
exit 1
fi
if [[ $# -gt 4 ]]; then
usage
fi
if ! command -v openssl &> /dev/null; then
log_error "OpenSSL is required but not installed"
exit 1
fi
}
detect_distro() {
log_info "[2/10] Detecting distribution..."
if [[ ! -f /etc/os-release ]]; then
log_error "Cannot detect distribution - /etc/os-release not found"
exit 1
fi
. /etc/os-release
case "$ID" in
ubuntu|debian)
PKG_MGR="apt"
PKG_INSTALL="apt-get install -y"
PKG_UPDATE="apt-get update && apt-get upgrade -y"
FIREWALL_CMD="ufw"
;;
almalinux|rocky|centos|rhel|ol|fedora)
PKG_MGR="dnf"
PKG_INSTALL="dnf install -y"
PKG_UPDATE="dnf update -y"
FIREWALL_CMD="firewalld"
;;
amzn)
PKG_MGR="yum"
PKG_INSTALL="yum install -y"
PKG_UPDATE="yum update -y"
FIREWALL_CMD="firewalld"
;;
*)
log_error "Unsupported distribution: $ID"
exit 1
;;
esac
log_info "Detected: $PRETTY_NAME using $PKG_MGR"
}
update_system() {
log_info "[3/10] Updating system packages..."
if [[ "$PKG_MGR" == "apt" ]]; then
apt-get update && apt-get upgrade -y
$PKG_INSTALL wget curl gnupg2 software-properties-common apt-transport-https ca-certificates lsb-release
else
$PKG_UPDATE
$PKG_INSTALL wget curl gnupg2 yum-utils
fi
}
add_mongodb_repository() {
log_info "[4/10] Adding MongoDB official repository..."
if [[ "$PKG_MGR" == "apt" ]]; then
curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | 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" > /etc/apt/sources.list.d/mongodb-org-8.0.list
apt-get update
else
rpm --import https://www.mongodb.org/static/pgp/server-8.0.asc
cat > /etc/yum.repos.d/mongodb-org-8.0.repo << EOF
[mongodb-org-8.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/\$releasever/mongodb-org/8.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-8.0.asc
EOF
fi
}
install_mongodb() {
log_info "[5/10] Installing MongoDB 8.0..."
$PKG_INSTALL mongodb-org
# Prevent automatic updates
if [[ "$PKG_MGR" == "apt" ]]; then
echo "mongodb-org hold" | dpkg --set-selections
echo "mongodb-org-database hold" | dpkg --set-selections
echo "mongodb-org-server hold" | dpkg --set-selections
echo "mongodb-org-mongos hold" | dpkg --set-selections
echo "mongodb-org-tools hold" | dpkg --set-selections
fi
}
create_ssl_certificates() {
log_info "[6/10] Creating SSL certificates..."
mkdir -p /etc/mongodb/ssl
# Generate self-signed certificate for testing
openssl req -new -x509 -days 365 -nodes \
-out /etc/mongodb/ssl/mongodb.pem \
-keyout /etc/mongodb/ssl/mongodb.pem \
-subj "/C=US/ST=State/L=City/O=Organization/CN=$MONGODB_IP"
chown -R mongod:mongod /etc/mongodb/ssl
chmod 700 /etc/mongodb/ssl
chmod 600 /etc/mongodb/ssl/mongodb.pem
log_warn "Using self-signed certificate. For production, use certificates from a trusted CA."
}
configure_mongodb() {
log_info "[7/10] Configuring MongoDB with security hardening..."
cat > /etc/mongod.conf << EOF
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,$MONGODB_IP
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
EOF
chmod 644 /etc/mongod.conf
chown root:root /etc/mongod.conf
}
configure_firewall() {
log_info "[8/10] Configuring firewall rules..."
if [[ "$FIREWALL_CMD" == "ufw" ]]; then
if command -v ufw &> /dev/null; then
ufw --force enable
ufw allow from $NETWORK_CIDR to any port 27017
ufw reload
fi
else
if command -v firewall-cmd &> /dev/null; then
systemctl enable --now firewalld
firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='$NETWORK_CIDR' port protocol='tcp' port='27017' accept"
firewall-cmd --reload
fi
fi
}
start_mongodb() {
log_info "[9/10] Starting and enabling MongoDB service..."
systemctl daemon-reload
systemctl enable mongod
systemctl start mongod
# Wait for MongoDB to start
sleep 10
}
create_admin_user() {
log_info "[10/10] Creating admin user and testing connection..."
# First, start MongoDB without authentication temporarily
sed -i 's/authorization: enabled/# authorization: enabled/' /etc/mongod.conf
systemctl restart mongod
sleep 5
# Create admin user
mongosh --tls --tlsAllowInvalidCertificates --eval "
use admin;
db.createUser({
user: '$ADMIN_USER',
pwd: '$ADMIN_PASSWORD',
roles: [
{ role: 'userAdminAnyDatabase', db: 'admin' },
{ role: 'readWriteAnyDatabase', db: 'admin' },
{ role: 'dbAdminAnyDatabase', db: 'admin' },
{ role: 'clusterAdmin', db: 'admin' }
]
});
"
# Re-enable authentication
sed -i 's/# authorization: enabled/authorization: enabled/' /etc/mongod.conf
systemctl restart mongod
sleep 5
}
verify_installation() {
log_info "Verifying MongoDB installation..."
if ! systemctl is-active --quiet mongod; then
log_error "MongoDB service is not running"
return 1
fi
if ! mongosh --tls --tlsAllowInvalidCertificates -u "$ADMIN_USER" -p "$ADMIN_PASSWORD" --authenticationDatabase admin --eval "db.adminCommand('ping')" &>/dev/null; then
log_error "Cannot connect to MongoDB with admin credentials"
return 1
fi
log_info "MongoDB 8.0 installation completed successfully!"
log_info "Admin user: $ADMIN_USER"
log_info "Admin password: $ADMIN_PASSWORD"
log_info "Connection string: mongodb://$ADMIN_USER:$ADMIN_PASSWORD@$MONGODB_IP:27017/?tls=true&authSource=admin"
log_warn "Store the admin password securely and change it if needed"
}
main() {
check_prerequisites "$@"
detect_distro
update_system
add_mongodb_repository
install_mongodb
create_ssl_certificates
configure_mongodb
configure_firewall
start_mongodb
create_admin_user
verify_installation
}
main "$@"
Review the script before running. Execute with: bash install.sh