Database Intermediate

Troubleshooting MongoDB ‘Connection Refused’ on Port 27017 on Ubuntu 22.04 LTS

Facing 'MongoDB connection refused' on Ubuntu 22.04 LTS? This guide diagnoses and resolves common issues preventing MongoDB from accepting connections on port 27017, from service status to firewall rules, ensuring your applications connect successfully.

👨‍💻
Senior Systems Architect • Verified in Staging Labs

Facing 'MongoDB connection refused' on Ubuntu 22.04 LTS? This guide diagnoses and resolves common issues preventing MongoDB from accepting connections on port 27017, from service status to firewall rules, ensuring your applications connect successfully.

When your application or mongosh client attempts to connect to a MongoDB instance on Ubuntu 22.04 LTS and encounters a "Connection Refused" error on port 27017, it signifies that the client successfully reached the server's IP address, but no process was actively listening on that specific port, or a firewall explicitly blocked the connection. This guide provides a comprehensive, step-by-step troubleshooting process to diagnose and resolve this common issue, getting your MongoDB instance back online and accessible.

Symptom & Error Signature

Users typically experience application outages or direct connection failures when attempting to interact with the MongoDB database. The error signature consistently points to a refused connection on the default MongoDB port, 27017.

From mongosh client:

mongosh

# Output may vary, but often includes:
# ...
# MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
#     at ConnectionPool.connect (/usr/local/lib/node_modules/mongosh/node_modules/mongodb/lib/sdam/topology.js:314:28)
#     at Topology.connect (/usr/local/lib/node_modules/mongosh/node_modules/mongodb/lib/sdam/topology.js:154:12)
#     at ServerSelector.selectServer (/usr/local/lib/node_modules/mongosh/node_modules/mongodb/lib/sdam/topology.js:1062:24)
#     at Topology.selectServer (/usr/local/lib/node_modules/mongosh/node_modules/mongodb/lib/sdam/topology.js:304:47)
#     at processTicksAndRejections (node:internal/process/task_queues:96:5)
#     at Timeout._onTimeout (/usr/local/lib/node_modules/mongosh/node_modules/mongodb/lib/sdam/topology.js:1255:40)
#     at listOnTimeout (node:internal/timers:564:17)
#     at processTimers (node:internal/timers:507:7) {
#   reason: TopologyDescription {
#     type: 'Unknown',
#     servers: Map(1) { 'localhost:27017' => [ServerDescription] },
#     stale: false,
#     compatible: true,
#     heartbeatFrequencyMS: 10000,
#     localThresholdMS: 15,
#     setName: null,
#     maxSetVersion: null,
#     maxElectionId: null,
#     commonWireVersion: null,
#     logicalSessionTimeoutMinutes: null
#   }
# }

From application logs (e.g., Node.js with Mongoose):

[Error] MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
    at _handleConnectionErrors (/app/node_modules/mongoose/lib/connection.js:779:11)
    at Connection.openUri (/app/node_modules/mongoose/lib/connection.js:754:11)
    at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:374:15)
    at Object.<anonymous> (/app/src/server.js:18:10)
    at Module._compile (node:internal/modules/cjs/loader:1256:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
    at Module.load (node:internal/modules/cjs/loader:1119:32)
    at Module._load (node:internal/modules/cjs/loader:960:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47 {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxSetVersion: null,
    maxElectionId: null,
    commonWireVersion: null,
    logicalSessionTimeoutMinutes: null
  }
}

Root Cause Analysis

The "Connection Refused" error typically stems from one or more of the following underlying issues:

  1. MongoDB Service Not Running: The mongod daemon, which is the core MongoDB process, is not active on the server. This is the most common cause.
  2. Incorrect bindIp Configuration: MongoDB is configured to listen only on 127.0.0.1 (localhost) within its /etc/mongod.conf file, but the client is attempting to connect from a different IP address (e.g., another server or a remote workstation).
  3. Firewall Blocking Port 27017: A local firewall (like UFW on Ubuntu) or a cloud provider's network security group (e.g., AWS Security Groups, Azure Network Security Groups, Google Cloud Firewall Rules) is preventing incoming connections to TCP port 27017.
  4. Corrupted Data Files or Journal: MongoDB might fail to start if its data files (/var/lib/mongodb) or journal files are corrupted, or if there's insufficient disk space.
  5. Incorrect Permissions: The mongodb user might lack the necessary read/write permissions for its data directory (/var/lib/mongodb) or log directory (/var/log/mongodb).
  6. Resource Exhaustion: While less common for "connection refused" at startup, severe memory pressure or disk I/O issues could indirectly prevent the mongod process from starting cleanly.

Step-by-Step Resolution

Follow these steps systematically to diagnose and resolve the "Connection Refused" error.

1. Verify MongoDB Service Status

The first and most critical step is to confirm that the MongoDB service (mongod) is running.

sudo systemctl status mongod

Expected Output for a running service:

● mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)
     Active: active (running) since Tue 2026-09-29 10:00:00 UTC; 10min ago
       Docs: https://docs.mongodb.org/manual
   Main PID: 1234 (mongod)
      Tasks: 16 (limit: 4676)
     Memory: 256.0M
        CPU: 1.500s
     CGroup: /system.slice/mongod.service
             └─1234 /usr/bin/mongod --config /etc/mongod.conf

If the service is not running (e.g., inactive (dead) or failed):

Attempt to start it and then immediately check its journal logs for specific error messages.

sudo systemctl start mongod
sudo systemctl status mongod

If it still fails or shows failed status, examine the logs:

sudo journalctl -xeu mongod --since "5 minutes ago"

Also, check the MongoDB specific log file:

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

The logs are your definitive source for understanding why MongoDB failed to start. Look for keywords like "exception", "ERROR", "permission denied", "Failed to acquire F_SETLK lock", "Out of memory", or "bad data file".

2. Check MongoDB Configuration for bindIp

By default, MongoDB often binds only to 127.0.0.1 (localhost) for security reasons. If your client is on a different machine or even a Docker container not using host networking, it won't be able to connect.

Open the MongoDB configuration file:

sudo nano /etc/mongod.conf

Locate the net: section and specifically the bindIp: directive.

Example mongod.conf snippet:

# mongod.conf

# ... other configurations ...

net:
  port: 27017
  bindIp: 127.0.0.1 # This line is critical!
# ...
  • If you need to connect from the same server but from a different network interface or a container (e.g., Docker bridge network): Ensure bindIp includes 127.0.0.1 and potentially other internal IPs, or 0.0.0.0 to listen on all available network interfaces.
  • If you need remote access from other machines: Change bindIp: 127.0.0.1 to bindIp: 0.0.0.0.
  • For specific IPs: You can list multiple IPs separated by commas, e.g., bindIp: 127.0.0.1,192.168.1.100.

Changing bindIp to 0.0.0.0 allows MongoDB to listen on all network interfaces. This significantly increases your security risk if not combined with proper firewall rules and MongoDB's built-in authentication/authorization. Always enable authentication and restrict network access with a firewall when exposing MongoDB.

After modifying mongod.conf, restart the MongoDB service for changes to take effect:

sudo systemctl restart mongod

3. Inspect Firewall Rules (UFW & Cloud Firewalls)

Even if MongoDB is running and configured to listen on the correct IP, a firewall can still block connections.

Check Ubuntu's Uncomplicated Firewall (UFW):

sudo ufw status verbose

Look for a rule allowing traffic on port 27017/tcp.

Example of an allowed rule:

Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
27017/tcp                  ALLOW IN    Anywhere                  # Allow MongoDB

If port 27017 is not allowed, or UFW is active and denying by default:

Add a rule to allow incoming TCP traffic on port 27017.

  • For local access only:
    sudo ufw allow from 127.0.0.1 to any port 27017
    sudo ufw reload
    
  • For remote access from a specific IP address (e.g., your application server's IP):
    sudo ufw allow from YOUR_CLIENT_IP_ADDRESS to any port 27017
    sudo ufw reload
    
  • For remote access from any IP (least secure, use with caution):
    sudo ufw allow 27017/tcp
    sudo ufw reload
    

When configuring firewall rules, always prioritize the principle of least privilege. Only allow access from necessary IP addresses or subnets. For production environments, exposing MongoDB directly to the internet is highly discouraged without strong authentication and TLS.

Cloud Provider Firewalls:

If your Ubuntu server is hosted in a cloud environment (AWS EC2, Azure VM, GCP Compute Engine), you'll also need to check the cloud provider's network security settings:

  • AWS: Security Groups associated with your EC2 instance.
  • Azure: Network Security Groups (NSGs) associated with your VM or subnet.
  • GCP: Firewall Rules in your VPC network.

Ensure these firewalls have an inbound rule allowing TCP traffic on port 27017 from the IP address(es) that need to connect to your MongoDB instance.

4. Verify Data Directory Permissions & Ownership

MongoDB requires specific permissions to write to its data and log directories. Incorrect permissions can prevent the service from starting.

Check the ownership and permissions of the MongoDB data and log directories:

ls -ld /var/lib/mongodb /var/log/mongodb

The output should typically show mongodb as the owner and group:

drwxr-xr-x 5 mongodb mongodb 4096 Sep 29 10:05 /var/lib/mongodb
drwxr-xr-x 2 mongodb mongodb 4096 Sep 29 10:00 /var/log/mongodb

If the ownership is incorrect (e.g., root), change it back to mongodb:

sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo chown -R mongodb:mongodb /var/log/mongodb

After correcting permissions, restart MongoDB:

sudo systemctl restart mongod

5. Check Disk Space

Insufficient disk space, especially on the partition hosting /var/lib/mongodb or /var/log/mongodb, can prevent MongoDB from starting or operating correctly.

df -h

Ensure there's adequate free space. If disk space is critically low, you'll need to free up space by deleting old logs, unused files, or extending the volume.

6. Review MongoDB Log File for Specific Errors

If MongoDB still fails to start after checking the above, the mongod.log file will contain the exact reason.

sudo tail -n 100 /var/log/mongodb/mongod.log

Look for specific error messages that indicate issues like:

  • Failed to acquire F_SETLK lock on /var/lib/mongodb/mongod.lock: This means another mongod process might be running (check ps aux | grep mongod), or a previous shutdown was unclean, leaving a stale lock file. You might need to remove mongod.lock after ensuring no mongod process is running:
    sudo rm /var/lib/mongodb/mongod.lock
    sudo systemctl start mongod
    

    Only remove the mongod.lock file if you are absolutely certain no other mongod process is active, otherwise, it can lead to data corruption.

  • DBException: next power of 2 size <= 16GB: Indicates a problem with data file size limits, often seen in older versions or specific configurations.
  • exception in initAndListen: NonExistentPath: Data directory /var/lib/mongodb not found.: The data directory is missing or misconfigured.

7. Reinstall MongoDB (Last Resort)

If all troubleshooting steps fail, and especially if you suspect data corruption (and have backups!), a clean reinstallation might be necessary.

This process will delete all existing MongoDB data unless you explicitly back up /var/lib/mongodb beforehand. Proceed with extreme caution.

  1. Stop MongoDB:

    sudo systemctl stop mongod
    
  2. Backup Data (Optional but Recommended):

    sudo tar -czvf /tmp/mongodb_backup_$(date +%Y%m%d%H%M%S).tar.gz /var/lib/mongodb
    
  3. Purge MongoDB packages and configuration:

    sudo apt remove --purge mongodb-org*
    
  4. Remove remaining data and log directories:

    sudo rm -rf /var/lib/mongodb
    sudo rm -rf /var/log/mongodb
    
  5. Reinstall MongoDB (follow official MongoDB documentation for the most current method):

    # Import the public key used by the package management system
    wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add - # For MongoDB 6.0
    # For MongoDB 7.0:
    # wget -qO - https://www.mongodb.org/static/pgp/server-7.0.asc | sudo apt-key add - 
    
    # Create a list file for MongoDB
    echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list # For 6.0
    # For MongoDB 7.0:
    # echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
    
    # Reload local package database
    sudo apt update
    
    # Install the MongoDB packages
    sudo apt install -y mongodb-org
    
  6. Start MongoDB:

    sudo systemctl start mongod
    sudo systemctl enable mongod
    
  7. Verify Status and Connectivity:

    sudo systemctl status mongod
    mongosh --port 27017 --eval "db.adminCommand({ ping: 1 })"
    

By meticulously following these steps, you should be able to identify and resolve the root cause of the "MongoDB socket connection failed connection refused port 27017" error on your Ubuntu 22.04 LTS system.

👨‍💻

Johnathon Wheeler

Senior Systems Architect & DevOps Engineer • Austin, TX

Connect on LinkedIn →

Johnathon has over 16 years of hands-on experience designing, debugging, and scaling Linux web hosting stacks, container clusters, and high-availability database architectures. Every guide on ButItWorkedLocal is independently tested against Debian 12, Ubuntu 24.04/22.04 LTS, Rocky Linux, and Docker environments to guarantee reproducibility in production.

🛡️

Our Production Verification Guarantee

Encountering a bug not covered here or running a non-standard kernel configuration? Our solutions are continually refined against real production incidents. Submit an environment trace for our editorial team to replicate.