Troubleshooting MongoDB 'Connection Refused' on Port 27017

Resolve MongoDB socket connection refused errors on port 27017. This guide covers firewall, service status, bind IP, and configuration issues for seamless database connectivity.


When your application attempts to connect to a MongoDB instance and encounters a “Connection Refused” error on port 27017, it signifies that the client’s connection request was actively rejected by the target server. This typically means that while the network path to the server might be open, there’s no process listening on the specified port, or a firewall is explicitly blocking the connection. This guide provides a systematic approach to diagnose and resolve this critical database connectivity issue, ensuring your MongoDB instance is accessible to your applications.

Symptom & Error Signature

Users will typically observe their applications failing to connect to the MongoDB database. This can manifest as blank pages, server-side error messages, or direct CLI connection failures.

Typical error messages you might encounter include:

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

MongooseError: connect ECONNREFUSED 127.0.0.1:27017
    at Connection.<anonymous> (/path/to/node_modules/mongoose/lib/connection.js:779:20)
    at Object.onceWrapper (node:events:628:28)
    at Connection.emit (node:events:513:28)
    at Connection.emit (/path/to/node_modules/mongoose/lib/connection.js:130:48)
    at Socket.<anonymous> (/path/to/node_modules/mongoose/lib/connection.js:730:16)
    at Socket.emit (node:events:513:28)
    at emitErrorNT (node:internal/process/next_tick:107:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

From the MongoDB shell (mongo or mongosh):

MongoDB shell version vX.Y.Z
connecting to: mongodb://127.0.0.1:27017/test
Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused calling connect()...

From network utilities (telnet or nc):

$ telnet 127.0.0.1 27017
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused

$ nc -zv 127.0.0.1 27017
nc: connect to 127.0.0.1 port 27017 (tcp) failed: Connection refused

Root Cause Analysis

The “Connection Refused” error almost always points to one of the following underlying issues:

  1. MongoDB Service Not Running: The mongod process, which is the core MongoDB database server, is not active on the machine. This is the most frequent cause.
  2. Firewall Blocking Connection: An active firewall (either on the host OS like UFW/iptables, or a cloud provider’s security group/network ACL) is configured to block incoming connections to port 27017. The client’s connection attempt is explicitly denied by the firewall.
  3. Incorrect bindIp Configuration: MongoDB is configured to listen only on specific IP addresses (e.g., 127.0.0.1 for localhost only), but the client application is attempting to connect from a different IP address (e.g., a remote server or a different network interface on the same host).
  4. Incorrect Port Configuration: While less common for the default 27017, MongoDB might be configured to listen on a non-standard port, but the client is still trying to connect to 27017.
  5. Resource Exhaustion or System Issues: In rare cases, the mongod process might fail to start due to issues like disk full, corrupted data files, too many open file descriptors, or other system-level constraints.
  6. SELinux/AppArmor Restrictions: Security enforcement modules (like SELinux on RHEL-based systems or AppArmor on Ubuntu) might be preventing mongod from binding to its port or accessing necessary resources, though this typically manifests as service startup failures rather than a direct “connection refused” if the service isn’t attempting to start at all.

Step-by-Step Resolution

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

1. Verify MongoDB Service Status

The first and most crucial step is to ensure that the MongoDB service is actually running.

sudo systemctl status mongod

Expected Output (Running):

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

If Active: inactive (dead) or failed: The service is not running. Try starting it:

sudo systemctl start mongod

Then check the status again. If it fails to start, investigate the service logs:

sudo journalctl -xeu mongod

Look for specific error messages that indicate why MongoDB failed to start. This might point to permission issues, configuration errors, or data corruption.

[!IMPORTANT] Always check journalctl -xeu mongod if the service fails to start or immediately stops after being started. This log provides critical insights into the startup process and any encountered errors.

2. Check Network Listener and Port Availability

If the service is running, verify that it’s listening on the expected port (27017) and IP address.

sudo ss -tuln | grep 27017
# Or for older systems:
# sudo netstat -tuln | grep 27017

Expected Output (Listening):

tcp   LISTEN 0      4096   127.0.0.1:27017      0.0.0.0:*
# Or if listening on all interfaces:
# tcp   LISTEN 0      4096   0.0.0.0:27017        0.0.0.0:*
  • If you see 127.0.0.1:27017, MongoDB is only listening on the local loopback interface. Remote connections will fail.
  • If you see 0.0.0.0:27017, MongoDB is listening on all available network interfaces, including external ones.
  • If no output is returned, MongoDB is either not running, or it’s configured to listen on a different port or interface that grep 27017 doesn’t match. In this case, re-verify Step 1.

3. Inspect MongoDB Configuration (mongod.conf)

MongoDB’s network binding is configured in its main configuration file, typically /etc/mongod.conf. The bindIp setting is critical here.

Open the configuration file for editing:

sudo nano /etc/mongod.conf

Locate the net: section and specifically the bindIp parameter:

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1 # COMMENT THIS LINE OUT or CHANGE IT

Common bindIp scenarios:

  • bindIp: 127.0.0.1: MongoDB will only accept connections from the local machine. This is the default and recommended for security if the application resides on the same server.
  • bindIp: 0.0.0.0: MongoDB will listen on all available network interfaces. Use this ONLY if you have proper firewall rules in place to restrict access, otherwise, your database will be publicly exposed.
  • bindIp: 127.0.0.1,<your_server_private_ip>: To allow connections from the local machine and a specific internal IP address (e.g., from another server in your private network).
  • bindIp: <your_server_public_ip>: If your application is external and directly connects to MongoDB, this allows connections on a specific public IP. Not generally recommended.

Resolution: If your application is trying to connect from a remote server or a different network interface and bindIp is set to 127.0.0.1, you need to modify it.

  • For applications on the same server: Keep bindIp: 127.0.0.1. Ensure your application also connects to 127.0.0.1:27017.
  • For applications on a different server (private network): Change bindIp to include the local server’s private IP, or 0.0.0.0 (with strict firewall rules).
    • Example for private IP: bindIp: 127.0.0.1,192.168.1.10 (replace with your server’s actual private IP).
    • Example for all interfaces (with caution): bindIp: 0.0.0.0

[!WARNING] Setting bindIp: 0.0.0.0 without properly configured external firewall rules (Step 4) will expose your MongoDB instance to the entire internet. This is a severe security vulnerability. Only use this if you fully understand the implications and have robust network security in place.

After making changes, save the file and restart the MongoDB service:

sudo systemctl restart mongod

Verify the service status and network listener again (Steps 1 & 2).

4. Examine Firewall Rules

Firewalls can block connections even if MongoDB is running and correctly configured. Check both OS-level firewalls and any cloud provider security groups.

4.1. UFW (Uncomplicated Firewall) on Ubuntu

Check UFW status:

sudo ufw status verbose

If UFW is active and MongoDB is meant to be accessed remotely, ensure port 27017 is allowed.

To allow access from a specific IP (most secure):

sudo ufw allow from <CLIENT_IP_ADDRESS>/32 to any port 27017
sudo ufw reload

Replace <CLIENT_IP_ADDRESS> with the actual IP address of the server or client that needs to connect to MongoDB.

To allow access from any IP (less secure, use with caution):

sudo ufw allow 27017/tcp
sudo ufw reload

[!WARNING] Allowing 27017/tcp from anywhere (implied by the command above without from clause) opens MongoDB to the public internet. Only do this if bindIp is restricted to an internal IP or if you have other network security controls in place.

4.2. Cloud Provider Security Groups / Network ACLs

If your MongoDB server is hosted on a cloud platform (AWS EC2, Azure VM, Google Cloud Compute Engine, etc.), you must check the cloud provider’s firewall settings:

  • AWS: Check the Security Group attached to your EC2 instance. Ensure an inbound rule exists for TCP port 27017, allowing traffic from your client’s IP address or the appropriate security group.
  • Azure: Review Network Security Groups (NSGs) associated with your VM’s network interface or subnet. Add an inbound security rule for TCP port 27017.
  • Google Cloud: Examine your VPC Firewall rules. Create or modify a rule to allow TCP traffic on port 27017 from the necessary source IP ranges.

These cloud firewalls often supersede OS-level firewalls and are a common source of “Connection Refused” for remote connections.

5. Verify Disk Space and Permissions

While less common for a direct “Connection Refused,” an inability to write to its data or log directories can prevent MongoDB from starting or operating correctly.

Check Disk Space:

df -h

Ensure there’s sufficient free space, especially on the partitions hosting /var/lib/mongodb and /var/log/mongodb.

Check Permissions:

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

MongoDB typically runs as the mongodb user and group. The directories /var/lib/mongodb and /var/log/mongodb (and their contents) should be owned by mongodb:mongodb.

If permissions are incorrect, fix them:

sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo chown mongodb:mongodb /var/log/mongodb
sudo systemctl restart mongod

6. Review MongoDB Log Files

Always consult the MongoDB log files for detailed error messages, especially if the service is failing to start or acting unexpectedly.

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

Start the service in another terminal after running tail -f to see real-time output. Look for any ERROR or FAILURE messages that provide specific reasons for non-startup or connection issues.

7. Ensure Consistent Configuration for Docker (if applicable)

If MongoDB is running inside a Docker container, the troubleshooting steps vary slightly:

  • Check container status:

    docker ps -a | grep mongo

    Ensure your MongoDB container is Up. If Exited, check logs: docker logs <container_id_or_name>.

  • Port Mapping: Verify that the Docker container’s port 27017 is correctly mapped to the host’s port 27017 (or another desired host port). In your docker run command or docker-compose.yml, look for the -p or ports entry:

    # Example docker run
    docker run -d --name my-mongo -p 27017:27017 mongo:latest
    
    # Example docker-compose.yml
    # services:
    #   mongo:
    #     image: mongo:latest
    #     ports:
    #       - "27017:27017"

    The format is HOST_PORT:CONTAINER_PORT.

  • bindIp inside Docker: For MongoDB running inside a container, it’s common and often necessary to set bindIp: 0.0.0.0 in its configuration, as the container’s network interface is usually isolated. Docker’s port mapping then handles exposing it to the host. This would typically be done via an environment variable or by mounting a custom mongod.conf into the container.

  • Host Firewall: Remember that even with Docker, the host machine’s firewall (UFW, iptables) still applies to traffic coming into the host before it reaches Docker’s port mappings. Ensure the host firewall allows traffic to the HOST_PORT (e.g., 27017).

By systematically working through these steps, you should be able to identify and resolve the root cause of your MongoDB “Connection Refused” error on port 27017.