Overview
MongoDB is a popular open-source NoSQL document database that stores data in flexible, JSON-like documents. This guide covers the installation of MongoDB 7.0 Community Edition on Ubuntu 22.04 LTS (Jammy Jellyfish) and includes production-ready configuration steps for optimal performance and security.
Key Features of MongoDB 7.0:
- Enhanced time-series collections
- Queryable encryption
- Improved change streams
- Better performance with clustered collections
- Native support for aggregation pipeline operators
Prerequisites
- Ubuntu 22.04 LTS (Jammy Jellyfish)
- Root or sudo privileges
- At least 2GB of RAM (4GB+ recommended for production)
- Sufficient disk space (recommended: 10GB+ for data storage)
- Active internet connection for package downloads
Installation Steps
Step 1: Install Required Dependencies
First, ensure the required packages for secure key management are installed:
1sudo apt-get install gnupg curl2curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \3 sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg \4 --dearmor5
6echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list7sudo apt-get update8sudo apt-get install -y mongodb-orgWhat this does:
gnupg: GNU Privacy Guard for secure key managementcurl: Downloads the MongoDB GPG key from the official server--dearmor: Converts the ASCII-armored key to binary format- The repository is added with proper GPG signature verification
mongodb-orgis a meta-package that includes:mongodb-org-server,mongodb-org-mongos,mongodb-org-shell,mongodb-org-tools, andmongodb-org-database
Step 2: Verify Installation
After installation, verify MongoDB was installed correctly:
1mongod --version2mongosh --versionExpected output should show MongoDB version 7.0.x.
System Optimization for Production
MongoDB requires specific system resource limits to perform optimally, especially in production environments. The default Linux limits are often insufficient for database workloads.
Check Current System Limits
Review your current system resource limits to see what needs to be adjusted:
1ulimit -aThis displays all current limits including:
- open files (
nofile): Maximum number of open file descriptors - max user processes (
nproc): Maximum number of processes - virtual memory (
vmem): Maximum amount of virtual memory - file size (
fsize): Maximum size of files that can be created
Configure User-Level Resource Limits
1sudo nano /etc/security/limits.conf2
3* soft nofile 640004* hard nofile 640005* soft nproc 640006* hard nproc 640007* soft memlock unlimited8* hard memlock unlimited9* soft stack unlimited10* hard stack unlimited11* soft fsize unlimited12* hard fsize unlimited13* soft cpu unlimited14* hard cpu unlimited15* soft vmem unlimited16* hard vmem unlimitedExplanation of limits:
nofile(64000): Allows MongoDB to handle many concurrent connections and open database filesnproc(64000): Ensures sufficient processes for MongoDB's multi-threaded operationsmemlock(unlimited): Allows MongoDB to lock memory pages to RAM, preventing swappingstack(unlimited): Stack size for thread operationsfsize(unlimited): Removes file size restrictions for database filescpu(unlimited): No CPU time restrictionsvmem(unlimited): Virtual memory limit
Note: The asterisk (*) applies these limits to all users. For production, consider creating a dedicated mongodb user and applying limits specifically to that user.
Configure Systemd Service Limits
1sudo nano /etc/systemd/system.conf2# and for3sudo nano /etc/systemd/user.conf4
5DefaultLimitNOFILE=640006DefaultLimitNPROC=640007DefaultLimitMEMLOCK=infinity8DefaultLimitSTACK=infinity9DefaultLimitFSIZE=infinity10DefaultLimitCPU=infinity11DefaultLimitVMEM=infinityThese settings apply to all systemd services. The system.conf affects system services, while user.conf affects user services.
Enable PAM Limits Module
1sudo nano /etc/pam.d/common-session2session required pam_limits.soThe PAM (Pluggable Authentication Module) limits module ensures that the limits defined in /etc/security/limits.conf are applied during user login sessions.
Apply Changes and Reload Systemd
1sudo systemctl daemon-reloadThis reloads the systemd daemon to apply the new configuration changes.
System Reboot and MongoDB Service Management
Reboot the System
After making these system-level changes, a reboot is recommended to ensure all limits take effect:
1sudo rebootStart and Enable MongoDB Service
After the system restarts, start MongoDB and enable it to run on system boot:
1sudo systemctl start mongod2sudo systemctl enable mongodService management commands:
start: Starts the MongoDB service immediatelyenable: Configures MongoDB to start automatically on system bootstatus: Check service status withsudo systemctl status mongodstop: Stop the service withsudo systemctl stop mongodrestart: Restart the service withsudo systemctl restart mongod
Verify MongoDB is Running
1sudo systemctl status mongodYou should see "active (running)" in the output. Additionally, check the MongoDB logs:
1sudo tail -f /var/log/mongodb/mongod.logNetwork Configuration
Configure Network Binding
By default, MongoDB only listens on localhost (127.0.0.1) for security reasons. To allow remote connections, modify the network binding:
1sudo nano /etc/mongod.conf2
3 bindIp: 0.0.0.0Security Warning: Binding to 0.0.0.0 allows connections from any network interface. This is convenient for development but not recommended for production without proper firewall rules and authentication enabled.
Alternative secure configurations:
- Bind to specific IP:
bindIp: 127.0.0.1,192.168.1.100(localhost + specific private IP) - Use firewall rules to restrict access to specific IP addresses
- Always enable authentication (covered below)
MongoDB Configuration File Structure
The /etc/mongod.conf file uses YAML format. Key sections include:
1# Storage settings2storage:3 dbPath: /var/lib/mongodb4 journal:5 enabled: true6
7# Network settings8net:9 port: 2701710 bindIp: 127.0.0.111
12# Security settings13security:14 authorization: enabled15
16# Logging17systemLog:18 destination: file19 path: /var/log/mongodb/mongod.log20 logAppend: trueAuthentication and User Management
MongoDB authentication ensures only authorized users can access your databases. After modifying network settings, it's crucial to set up proper authentication.
Create Root Administrator User
1mongosh2use admin3
4db.createUser({5 user: "admin",6 pwd: "123",7 roles: [{ role: "root", db: "admin" }]8})Understanding MongoDB Roles:
root: Provides superuser access to all databases and administrative functionsreadWrite: Read and write access to a specific databaseread: Read-only access to a specific databasedbAdmin: Database administration (indexes, stats, etc.)userAdmin: Manage users and rolesclusterAdmin: Cluster administration for sharded or replica set deployments
Security Best Practice: Never use simple passwords like "123" in production. Use strong passwords with a mix of uppercase, lowercase, numbers, and special characters (minimum 16 characters recommended).
Enable Authentication in Configuration
After creating the admin user, enable authentication in the MongoDB configuration:
1sudo nano /etc/mongod.confAdd or modify the security section:
1security:2 authorization: enabled1sudo systemctl restart mongodAfter restart, all connections will require authentication. To connect with the admin user:
1mongosh -u admin -p 1232# Or for better security, enter password interactively:3mongosh -u admin -pCreate Application-Specific Database Users
Best practice is to create separate users for each application or database with minimal necessary privileges:
1db.createUser({2 user: "usr",3 pwd: "123", // Choose a secure password4 roles: [{ role: "readWrite", db: "mydatabase" }]5})This creates a user with read/write access limited to the mydatabase database. The user cannot access other databases or perform administrative tasks.
Additional user creation examples:
1# Create a read-only user for reporting2db.createUser({3 user: "reporter",4 pwd: "SecurePassword456!",5 roles: [{ role: "read", db: "mydatabase" }]6})7
8# Create a user with access to multiple databases9db.createUser({10 user: "multidb_user",11 pwd: "AnotherSecurePass789!",12 roles: [13 { role: "readWrite", db: "database1" },14 { role: "read", db: "database2" }15 ]16})17
18# Create a database administrator (not server admin)19db.createUser({20 user: "dbadmin",21 pwd: "DbAdminPass321!",22 roles: [{ role: "dbAdmin", db: "mydatabase" }]23})Update User Password
1mongosh -u admin -p2use admin3db.updateUser("admin", { pwd: "123" })You can also update other user properties:
1# Update user roles2db.updateUser("usr", { 3 roles: [4 { role: "readWrite", db: "mydatabase" },5 { role: "read", db: "anotherdatabase" }6 ]7})8
9# Grant additional roles to existing user10db.grantRolesToUser("usr", [11 { role: "dbAdmin", db: "mydatabase" }12])13
14# Revoke roles from user15db.revokeRolesFromUser("usr", [16 { role: "dbAdmin", db: "mydatabase" }17])List and Manage Users
1use admin2db.getUsers()Additional user management commands:
1# Get information about a specific user2db.getUser("admin")3
4# Delete a user5db.dropUser("username")6
7# List all users across all databases (requires admin privileges)8use admin9db.system.users.find()Additional Configuration and Optimization
Firewall Configuration (UFW)
If you're allowing remote connections, configure the firewall to restrict access:
1# Allow MongoDB port from specific IP2sudo ufw allow from 192.168.1.0/24 to any port 270173
4# Or allow from specific IP address5sudo ufw allow from 192.168.1.50 to any port 270176
7# Enable firewall8sudo ufw enable9
10# Check firewall status11sudo ufw statusPerformance Tuning
Disable Transparent Huge Pages (THP)
MongoDB recommends disabling THP for better performance:
1# Create a systemd service to disable THP2sudo nano /etc/systemd/system/disable-thp.serviceAdd the following content:
1[Unit]2Description=Disable Transparent Huge Pages (THP)3DefaultDependencies=no4After=sysinit.target local-fs.target5Before=mongod.service6
7[Service]8Type=oneshot9ExecStart=/bin/sh -c 'echo never | tee /sys/kernel/mm/transparent_hugepage/enabled > /dev/null'10ExecStart=/bin/sh -c 'echo never | tee /sys/kernel/mm/transparent_hugepage/defrag > /dev/null'11
12[Install]13WantedBy=basic.targetEnable the service:
1sudo systemctl daemon-reload2sudo systemctl enable disable-thp3sudo systemctl start disable-thpConfigure Swappiness
Reduce swap usage for better database performance:
1# Check current swappiness2cat /proc/sys/vm/swappiness3
4# Set swappiness to 1 (persistent)5echo "vm.swappiness = 1" | sudo tee -a /etc/sysctl.conf6sudo sysctl -pConnection String Examples
Once authentication is enabled, connect to MongoDB using connection strings:
1# Basic connection2mongosh "mongodb://admin:123@localhost:27017/admin"3
4# Connection with authentication database specified5mongosh "mongodb://usr:123@localhost:27017/mydatabase?authSource=admin"6
7# Remote connection8mongosh "mongodb://usr:[email protected]:27017/mydatabase"9
10# Connection string for applications (Node.js example)11mongodb://usr:password@localhost:27017/mydatabase?authSource=adminMonitoring and Maintenance
Check Database Statistics
1# Connect to MongoDB2mongosh -u admin -p3
4# Show all databases5show dbs6
7# Switch to a database8use mydatabase9
10# Show collections11show collections12
13# Get database stats14db.stats()15
16# Get collection stats17db.collectionName.stats()18
19# Check current operations20db.currentOp()21
22# Server status23db.serverStatus()Enable MongoDB Logs Rotation
Configure log rotation to prevent log files from consuming too much disk space:
1sudo nano /etc/logrotate.d/mongodAdd the following:
/var/log/mongodb/mongod.log {
daily
rotate 7
compress
delaycompress
notifempty
missingok
sharedscripts
postrotate
/bin/kill -SIGUSR1 $(cat /var/run/mongodb/mongod.pid 2>/dev/null) 2>/dev/null || true
endscript
}
Backup and Restore
Create a Backup
1# Backup all databases2mongodump --username admin --password 123 --authenticationDatabase admin --out /backup/mongodb/$(date +%Y%m%d)3
4# Backup specific database5mongodump --username usr --password 123 --authenticationDatabase admin --db mydatabase --out /backup/mongodb/mydatabase6
7# Backup specific collection8mongodump --db mydatabase --collection mycollection --out /backup/mongodb/Restore from Backup
1# Restore all databases2mongorestore --username admin --password 123 --authenticationDatabase admin /backup/mongodb/20260114/3
4# Restore specific database5mongorestore --username admin --password 123 --authenticationDatabase admin --db mydatabase /backup/mongodb/mydatabase6
7# Drop existing data before restoring8mongorestore --drop --username admin --password 123 --authenticationDatabase admin /backup/mongodb/Troubleshooting
Common Issues and Solutions
MongoDB Service Won't Start
1# Check service status and logs2sudo systemctl status mongod3sudo journalctl -u mongod -n 504
5# Check log file6sudo tail -100 /var/log/mongodb/mongod.log7
8# Verify permissions9sudo chown -R mongodb:mongodb /var/lib/mongodb10sudo chown -R mongodb:mongodb /var/log/mongodbConnection Refused
- Verify MongoDB is running:
sudo systemctl status mongod - Check bind IP in
/etc/mongod.conf - Verify firewall rules:
sudo ufw status - Check if port is listening:
sudo netstat -tulpn | grep 27017
Authentication Failed
- Verify user exists:
db.getUsers()(as admin) - Ensure using correct authentication database
- Check if authorization is enabled in config
- Verify password is correct
Performance Issues
1# Check system resources2htop3df -h4free -h5
6# MongoDB profiling7use mydatabase8db.setProfilingLevel(2) # Log all operations9db.system.profile.find().pretty()10
11# Analyze slow queries12db.system.profile.find({ millis: { $gt: 100 } }).sort({ ts: -1 })13
14# Check index usage15db.collection.explain("executionStats").find({field: "value"})Security Checklist
- ✅ Enable authentication
- ✅ Use strong passwords (16+ characters)
- ✅ Create separate users for different applications
- ✅ Apply principle of least privilege (minimal roles)
- ✅ Configure firewall rules
- ✅ Bind to specific IP addresses (not 0.0.0.0 in production)
- ✅ Enable SSL/TLS for encrypted connections
- ✅ Keep MongoDB updated
- ✅ Regular backups
- ✅ Monitor logs for suspicious activity
- ✅ Disable MongoDB HTTP status interface
- ✅ Use VPN or SSH tunneling for remote access
References and Additional Resources
- MongoDB Official Documentation
- MongoDB Security Checklist
- MongoDB Production Notes
- MongoDB Performance Best Practices
- MongoDB University - Free courses and certifications