Top Tags

Install MongoDB 7.0 on Ubuntu 22.04 Jammy

Complete guide to installing and configuring MongoDB 7.0 on Ubuntu 22.04 Jammy with production-ready settings

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:

bash
1sudo apt-get install gnupg curl
2curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
3 sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg \
4 --dearmor
5
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.list
7sudo apt-get update
8sudo apt-get install -y mongodb-org

What this does:

  • gnupg: GNU Privacy Guard for secure key management
  • curl: 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-org is a meta-package that includes: mongodb-org-server, mongodb-org-mongos, mongodb-org-shell, mongodb-org-tools, and mongodb-org-database

Step 2: Verify Installation

After installation, verify MongoDB was installed correctly:

bash
1mongod --version
2mongosh --version

Expected 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:

bash
1ulimit -a

This 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

bash
1sudo nano /etc/security/limits.conf
2
3* soft nofile 64000
4* hard nofile 64000
5* soft nproc 64000
6* hard nproc 64000
7* soft memlock unlimited
8* hard memlock unlimited
9* soft stack unlimited
10* hard stack unlimited
11* soft fsize unlimited
12* hard fsize unlimited
13* soft cpu unlimited
14* hard cpu unlimited
15* soft vmem unlimited
16* hard vmem unlimited

Explanation of limits:

  • nofile (64000): Allows MongoDB to handle many concurrent connections and open database files
  • nproc (64000): Ensures sufficient processes for MongoDB's multi-threaded operations
  • memlock (unlimited): Allows MongoDB to lock memory pages to RAM, preventing swapping
  • stack (unlimited): Stack size for thread operations
  • fsize (unlimited): Removes file size restrictions for database files
  • cpu (unlimited): No CPU time restrictions
  • vmem (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

bash
1sudo nano /etc/systemd/system.conf
2# and for
3sudo nano /etc/systemd/user.conf
4
5DefaultLimitNOFILE=64000
6DefaultLimitNPROC=64000
7DefaultLimitMEMLOCK=infinity
8DefaultLimitSTACK=infinity
9DefaultLimitFSIZE=infinity
10DefaultLimitCPU=infinity
11DefaultLimitVMEM=infinity

These settings apply to all systemd services. The system.conf affects system services, while user.conf affects user services.

Enable PAM Limits Module

bash
1sudo nano /etc/pam.d/common-session
2session required pam_limits.so

The 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

bash
1sudo systemctl daemon-reload

This 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:

bash
1sudo reboot

Start and Enable MongoDB Service

After the system restarts, start MongoDB and enable it to run on system boot:

bash
1sudo systemctl start mongod
2sudo systemctl enable mongod

Service management commands:

  • start: Starts the MongoDB service immediately
  • enable: Configures MongoDB to start automatically on system boot
  • status: Check service status with sudo systemctl status mongod
  • stop: Stop the service with sudo systemctl stop mongod
  • restart: Restart the service with sudo systemctl restart mongod

Verify MongoDB is Running

bash
1sudo systemctl status mongod

You should see "active (running)" in the output. Additionally, check the MongoDB logs:

bash
1sudo tail -f /var/log/mongodb/mongod.log

Network 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:

bash
1sudo nano /etc/mongod.conf
2
3 bindIp: 0.0.0.0

Security 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:

yaml
1# Storage settings
2storage:
3 dbPath: /var/lib/mongodb
4 journal:
5 enabled: true
6
7# Network settings
8net:
9 port: 27017
10 bindIp: 127.0.0.1
11
12# Security settings
13security:
14 authorization: enabled
15
16# Logging
17systemLog:
18 destination: file
19 path: /var/log/mongodb/mongod.log
20 logAppend: true

Authentication 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

bash
1mongosh
2use admin
3
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 functions
  • readWrite: Read and write access to a specific database
  • read: Read-only access to a specific database
  • dbAdmin: Database administration (indexes, stats, etc.)
  • userAdmin: Manage users and roles
  • clusterAdmin: 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:

bash
1sudo nano /etc/mongod.conf

Add or modify the security section:

yaml
1security:
2 authorization: enabled
bash
1sudo systemctl restart mongod

After restart, all connections will require authentication. To connect with the admin user:

bash
1mongosh -u admin -p 123
2# Or for better security, enter password interactively:
3mongosh -u admin -p

Create Application-Specific Database Users

Best practice is to create separate users for each application or database with minimal necessary privileges:

bash
1db.createUser({
2 user: "usr",
3 pwd: "123", // Choose a secure password
4 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:

bash
1# Create a read-only user for reporting
2db.createUser({
3 user: "reporter",
4 pwd: "SecurePassword456!",
5 roles: [{ role: "read", db: "mydatabase" }]
6})
7
8# Create a user with access to multiple databases
9db.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

bash
1mongosh -u admin -p
2use admin
3db.updateUser("admin", { pwd: "123" })

You can also update other user properties:

bash
1# Update user roles
2db.updateUser("usr", {
3 roles: [
4 { role: "readWrite", db: "mydatabase" },
5 { role: "read", db: "anotherdatabase" }
6 ]
7})
8
9# Grant additional roles to existing user
10db.grantRolesToUser("usr", [
11 { role: "dbAdmin", db: "mydatabase" }
12])
13
14# Revoke roles from user
15db.revokeRolesFromUser("usr", [
16 { role: "dbAdmin", db: "mydatabase" }
17])

List and Manage Users

bash
1use admin
2db.getUsers()

Additional user management commands:

bash
1# Get information about a specific user
2db.getUser("admin")
3
4# Delete a user
5db.dropUser("username")
6
7# List all users across all databases (requires admin privileges)
8use admin
9db.system.users.find()

Additional Configuration and Optimization

Firewall Configuration (UFW)

If you're allowing remote connections, configure the firewall to restrict access:

bash
1# Allow MongoDB port from specific IP
2sudo ufw allow from 192.168.1.0/24 to any port 27017
3
4# Or allow from specific IP address
5sudo ufw allow from 192.168.1.50 to any port 27017
6
7# Enable firewall
8sudo ufw enable
9
10# Check firewall status
11sudo ufw status

Performance Tuning

Disable Transparent Huge Pages (THP)

MongoDB recommends disabling THP for better performance:

bash
1# Create a systemd service to disable THP
2sudo nano /etc/systemd/system/disable-thp.service

Add the following content:

ini
1[Unit]
2Description=Disable Transparent Huge Pages (THP)
3DefaultDependencies=no
4After=sysinit.target local-fs.target
5Before=mongod.service
6
7[Service]
8Type=oneshot
9ExecStart=/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.target

Enable the service:

bash
1sudo systemctl daemon-reload
2sudo systemctl enable disable-thp
3sudo systemctl start disable-thp

Configure Swappiness

Reduce swap usage for better database performance:

bash
1# Check current swappiness
2cat /proc/sys/vm/swappiness
3
4# Set swappiness to 1 (persistent)
5echo "vm.swappiness = 1" | sudo tee -a /etc/sysctl.conf
6sudo sysctl -p

Connection String Examples

Once authentication is enabled, connect to MongoDB using connection strings:

bash
1# Basic connection
2mongosh "mongodb://admin:123@localhost:27017/admin"
3
4# Connection with authentication database specified
5mongosh "mongodb://usr:123@localhost:27017/mydatabase?authSource=admin"
6
7# Remote connection
8mongosh "mongodb://usr:[email protected]:27017/mydatabase"
9
10# Connection string for applications (Node.js example)
11mongodb://usr:password@localhost:27017/mydatabase?authSource=admin

Monitoring and Maintenance

Check Database Statistics

bash
1# Connect to MongoDB
2mongosh -u admin -p
3
4# Show all databases
5show dbs
6
7# Switch to a database
8use mydatabase
9
10# Show collections
11show collections
12
13# Get database stats
14db.stats()
15
16# Get collection stats
17db.collectionName.stats()
18
19# Check current operations
20db.currentOp()
21
22# Server status
23db.serverStatus()

Enable MongoDB Logs Rotation

Configure log rotation to prevent log files from consuming too much disk space:

bash
1sudo nano /etc/logrotate.d/mongod

Add 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

bash
1# Backup all databases
2mongodump --username admin --password 123 --authenticationDatabase admin --out /backup/mongodb/$(date +%Y%m%d)
3
4# Backup specific database
5mongodump --username usr --password 123 --authenticationDatabase admin --db mydatabase --out /backup/mongodb/mydatabase
6
7# Backup specific collection
8mongodump --db mydatabase --collection mycollection --out /backup/mongodb/

Restore from Backup

bash
1# Restore all databases
2mongorestore --username admin --password 123 --authenticationDatabase admin /backup/mongodb/20260114/
3
4# Restore specific database
5mongorestore --username admin --password 123 --authenticationDatabase admin --db mydatabase /backup/mongodb/mydatabase
6
7# Drop existing data before restoring
8mongorestore --drop --username admin --password 123 --authenticationDatabase admin /backup/mongodb/

Troubleshooting

Common Issues and Solutions

MongoDB Service Won't Start

bash
1# Check service status and logs
2sudo systemctl status mongod
3sudo journalctl -u mongod -n 50
4
5# Check log file
6sudo tail -100 /var/log/mongodb/mongod.log
7
8# Verify permissions
9sudo chown -R mongodb:mongodb /var/lib/mongodb
10sudo chown -R mongodb:mongodb /var/log/mongodb

Connection Refused

  1. Verify MongoDB is running: sudo systemctl status mongod
  2. Check bind IP in /etc/mongod.conf
  3. Verify firewall rules: sudo ufw status
  4. Check if port is listening: sudo netstat -tulpn | grep 27017

Authentication Failed

  1. Verify user exists: db.getUsers() (as admin)
  2. Ensure using correct authentication database
  3. Check if authorization is enabled in config
  4. Verify password is correct

Performance Issues

bash
1# Check system resources
2htop
3df -h
4free -h
5
6# MongoDB profiling
7use mydatabase
8db.setProfilingLevel(2) # Log all operations
9db.system.profile.find().pretty()
10
11# Analyze slow queries
12db.system.profile.find({ millis: { $gt: 100 } }).sort({ ts: -1 })
13
14# Check index usage
15db.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