Database Intermediate

Troubleshooting MongoDB Socket Connection Refused on Ubuntu 20.04 (Port 27017)

Fix 'MongoDB socket connection failed connection refused port 27017' on Ubuntu 20.04 LTS. Diagnose firewall, service status, bind IP, and data corruption issues quickly.

👨‍💻
Senior Systems Architect • Verified in Staging Labs

Fix 'MongoDB socket connection failed connection refused port 27017' on Ubuntu 20.04 LTS. Diagnose firewall, service status, bind IP, and data corruption issues quickly.

When deploying or managing applications that rely on MongoDB, encountering a "socket connection failed connection refused" error on port 27017 is a common hurdle. This error indicates that your client application or mongo shell is unable to establish a TCP connection to the MongoDB daemon (mongod) running on your Ubuntu 20.04 LTS server. It's a critical issue that can prevent your entire application stack from functioning. This guide will walk you through systematic troubleshooting steps to diagnose and resolve this problem, ensuring your MongoDB instance is accessible and operational.

Symptom & Error Signature

Users typically encounter this error when attempting to connect to MongoDB from a client application, a command-line utility like mongo or mongosh, or via a network test. The specific error message may vary slightly depending on the client driver or tool used, but the core issue of "connection refused" on port 27017 remains consistent.

Typical Error Output:

From mongo Shell / mongosh:

MongoDB shell version v4.4.11
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Error: connect ECONNREFUSED 127.0.0.1:27017 at connection_string_resolver.js:521:19
Failed to connect to 127.0.0.1:27017 in 5000ms, reason: connection refused
Error: Could not connect to the server.

From a Node.js Application (example using mongoose):

MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
    at Timeout._onTimeout (/app/node_modules/mongodb/lib/sdam/topology.js:290:38)
    at listOnTimeout (internal/timers.js:557:17)
    at processTimers (internal/timers.js:500:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { '127.0.0.1:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxSetVersion: null,
    maxElectionId: null,
    minWireVersion: 0,
    maxWireVersion: 0,
    roundTripTime: -1,
    hosts: [],
    passives: [],
    arbiters: [],
    primary: null,
    me: null,
    tag: null,
    sessionTimeoutMinutes: null,
    totalHostTimeMS: 0,
    topologyType: 'Unknown'
  }
}

From telnet or nc (netcat):

telnet localhost 27017
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused
nc -zv localhost 27017
nc: connect to localhost (127.0.0.1) port 27017 (tcp) failed: Connection refused

Root Cause Analysis

A "connection refused" error signifies that a connection attempt was explicitly denied by the target machine, rather than simply timing out. This denial can stem from several underlying issues, often related to the MongoDB service itself or the network stack.

Common root causes include:

  1. MongoDB Service Not Running: The mongod daemon is either stopped, failed to start, or crashed. This is the most frequent cause.
  2. Firewall Blocking Port 27017: A firewall (e.g., UFW, iptables) on the server is preventing incoming connections on port 27017.
  3. Incorrect bindIp Configuration: MongoDB is configured to listen only on localhost (127.0.0.1) while the client is attempting to connect from a different IP address, or it's bound to an incorrect network interface.
  4. Data Directory Issues: Permissions problems on /var/lib/mongodb, a corrupted mongod.lock file, or insufficient disk space can prevent mongod from starting correctly.
  5. System Resource Limitations: The server might be experiencing high CPU, RAM, or I/O load, or the mongod process was terminated by the OOM (Out Of Memory) killer.
  6. Incorrect Port: The client is attempting to connect to the wrong port, or MongoDB is configured to listen on a non-standard port.
  7. Network Interface Unavailability: If bindIp is set to a specific IP, and that network interface is down or not configured, MongoDB won't be able to listen.

Step-by-Step Resolution

Follow these steps systematically to diagnose and resolve the "connection refused" error.

1. Verify MongoDB Service Status

The first step is to confirm if the mongod service is actually running.

sudo systemctl status mongod

Expected Output (if running):

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

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

Examine the journalctl logs for mongod to understand why it failed to start:

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

Look for specific error messages that indicate the problem, such as:

  • Failed to start MongoDB Database Server.
  • exception in initAndListen: NonExistentPath: Data directory /var/lib/mongodb not found.
  • Failed to unlink socket file /tmp/mongodb-27017.sock (often due to mongod crash and improper cleanup).
  • Permission denied errors related to data or log directories.

Try to start or restart the service:

sudo systemctl start mongod
sudo systemctl enable mongod # Ensures it starts on boot

Then re-check the status:

sudo systemctl status mongod

2. Check Firewall Configuration (UFW)

If the mongod service is running, but you still cannot connect, especially from a remote machine, a firewall is a likely culprit. Ubuntu 20.04 commonly uses UFW (Uncomplicated Firewall).

Check UFW status:

sudo ufw status verbose

Look for rules allowing incoming TCP connections on port 27017. If 27017 is not listed or explicitly denied, you need to allow it.

Allow incoming connections on port 27017:

sudo ufw allow 27017/tcp
sudo ufw reload # Apply the new rules

If you need to allow connections only from specific IP addresses (highly recommended for production environments), use:

sudo ufw allow from YOUR_CLIENT_IP to any port 27017
sudo ufw reload

For testing, you might temporarily disable UFW with sudo ufw disable to rule it out, but never leave your firewall disabled in a production environment. Re-enable it with sudo ufw enable and then configure specific rules.

If you are using iptables directly (less common on modern Ubuntu installations without manual intervention):

sudo iptables -L -n | grep 27017

If rules are missing, you would add them (e.g., sudo iptables -A INPUT -p tcp --dport 27017 -j ACCEPT). However, managing iptables directly is complex; UFW is preferred.

3. Inspect MongoDB Configuration (bindIp)

MongoDB's configuration file (/etc/mongod.conf) dictates which IP addresses the mongod daemon listens on. By default, it often binds to 127.0.0.1 (localhost) for security, meaning only connections from the same server are permitted.

Edit the MongoDB configuration file:

sudo nano /etc/mongod.conf

Locate the net section and specifically the bindIp directive.

Example bindIp configurations:

  • bindIp: 127.0.0.1: MongoDB only accepts connections from the local machine. This is secure for applications running on the same server but prevents remote access.
  • bindIp: 0.0.0.0: MongoDB accepts connections from all network interfaces. This allows remote connections but is highly insecure without proper authentication and firewall rules.
  • bindIp: 127.0.0.1,YOUR_SERVER_IP: MongoDB accepts connections from localhost and a specific IP address (e.g., your server's public or private IP). This is a good balance for allowing specific remote connections.
# /etc/mongod.conf snippet
net:
  port: 27017
  bindIp: 127.0.0.1 # Change this if you need remote access

If your application or client is on a different server, you must change bindIp to 0.0.0.0 or to the specific IP address(es) your client will connect from, including your server's own network interface IP.

Example for remote access (use with caution):

# /etc/mongod.conf snippet
net:
  port: 27017
  bindIp: 0.0.0.0 # WARNING: Allows connections from anywhere. Secure with firewall and authentication!

Example for specific remote access:

# /etc/mongod.conf snippet
net:
  port: 27017
  bindIp: 127.0.0.1,192.168.1.100 # Allows local connections and from 192.168.1.100

Setting bindIp: 0.0.0.0 without robust firewall rules and strong MongoDB authentication enabled (e.g., SCRAM-SHA-256 with user roles) is a significant security risk. Your MongoDB instance will be exposed to the public internet, making it vulnerable to unauthorized access and data breaches. Always enable authentication in production.

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

sudo systemctl restart mongod

4. Validate Data Directory Permissions & Integrity

Incorrect permissions or a corrupted mongod.lock file in MongoDB's data directory (/var/lib/mongodb by default) can prevent the service from starting.

Check permissions:

sudo ls -ld /var/lib/mongodb
sudo ls -l /var/lib/mongodb

The directory and its contents should typically be owned by the mongodb user and group.

drwxr-xr-x 5 mongodb mongodb 4096 Sep  9 10:00 /var/lib/mongodb

If the ownership is incorrect, fix it:

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

Check for mongod.lock:

Sometimes, after an unclean shutdown, a stale mongod.lock file can prevent mongod from starting.

sudo ls -l /var/lib/mongodb/mongod.lock

If this file exists and mongod is not running (verify with sudo systemctl status mongod), you can safely remove it.

> [!WARNING]
> Only remove `mongod.lock` if you are absolutely sure that `mongod` is not running. Removing it while `mongod` is active can lead to data corruption. Always back up your data if you are unsure.

sudo rm /var/lib/mongodb/mongod.lock

After addressing permissions or removing the lock file, attempt to restart MongoDB:

sudo systemctl restart mongod

5. Review System Logs for OOM Killer or Other Issues

Check the system logs for signs of the Out Of Memory (OOM) killer terminating the mongod process, or other low-level system errors.

dmesg -T | grep -i oom

If you see Out of memory: Kill process <PID> (mongod), it means your server ran out of RAM, and the kernel terminated MongoDB. You'll need to either:

  • Increase server RAM.
  • Reduce MongoDB's memory footprint or other applications' usage.
  • Configure a swap file if one isn't present, although this is a fallback, not a solution for chronically low RAM.

You can also look for any other critical errors in the main system journal:

sudo journalctl -r -p err --no-pager

6. Network Connectivity Test

If MongoDB is running and configured correctly, ensure basic network connectivity using ss (socket statistics) and telnet (or nc).

Check if MongoDB is listening on port 27017:

sudo ss -tulnp | grep 27017

Expected output (showing mongod listening):

tcp LISTEN 0      128    127.0.0.1:27017      0.0.0.0:*    users:(("mongod",pid=12345,fd=10))

If you see 0.0.0.0:27017, it's listening on all interfaces. If it only shows 127.0.0.1:27017, it's local only. If no output, mongod is not listening, likely due to one of the above issues.

Test connectivity from the client:

From the machine where your application or mongo shell is running, try to telnet to the MongoDB server's IP and port:

telnet YOUR_MONGO_SERVER_IP 27017

If this command connects successfully (screen clears or shows connected message), then the network path and MongoDB listener are working, and the problem might be specific to your application's connection string or MongoDB authentication. If it still says "connection refused", then the issue is still on the MongoDB server side (firewall, bindIp, or service status).

By systematically following these steps, you should be able to identify and resolve the "MongoDB socket connection failed connection refused port 27017" error on your Ubuntu 20.04 LTS server. Remember to prioritize security by properly configuring firewalls and enabling authentication, especially when allowing remote access.

👨‍💻

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.