Database Intermediate

Troubleshooting MongoDB Connection Refused: Port 27017 on Windows WSL2 Ubuntu

Fix 'MongoDB socket connection failed connection refused port 27017' error on Windows WSL2 Ubuntu. Diagnose and resolve MongoDB connection issues effectively.

👨‍💻
Senior Systems Architect • Verified in Staging Labs

Fix 'MongoDB socket connection failed connection refused port 27017' error on Windows WSL2 Ubuntu. Diagnose and resolve MongoDB connection issues effectively.

When developing or hosting applications on Windows using the Windows Subsystem for Linux 2 (WSL2) with an Ubuntu distribution, encountering a "MongoDB socket connection failed connection refused" error on port 27017 is a common hurdle. This usually indicates that your application running either within WSL2 or on the Windows host cannot establish a network connection to the MongoDB daemon running inside your Ubuntu WSL2 instance. This guide will walk you through diagnosing and resolving this persistent connection issue.

Symptom & Error Signature

Users will typically observe their application failing to start or operate correctly, displaying connection errors in logs or on the console. Attempts to connect via the mongo shell (now mongosh) may also fail.

Typical error messages you might encounter:

From application logs (e.g., Node.js, Python, Java):

MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
    at _handleConnectionErrors (/path/to/node_modules/mongoose/lib/connection.js:770:11)
    at Connection.openUri (/path/to/node_modules/mongoose/lib/connection.js:745:11)
    ...
Reason: connect ECONNREFUSED 127.0.0.1:27017
pymongo.errors.ServerSelectionTimeoutError: 127.0.0.1:27017: Connection refused

From the MongoDB shell (mongosh) within WSL2:

mongosh
Current Mongosh Log ID:        65a7d...
Connecting to:                 mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0
MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017

From the MongoDB shell (mongosh) on Windows attempting to connect to WSL2 IP:

mongosh --host <WSL2_IP> --port 27017
Connecting to:                 mongodb://<WSL2_IP>:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0
MongoNetworkError: connect ECONNREFUSED <WSL2_IP>:27017

Root Cause Analysis

The "connection refused" error signifies that the client's connection attempt was actively rejected by the target machine, rather than merely timing out or being unreachable. This points to several potential underlying issues:

  1. MongoDB Service Not Running: The most common cause. The mongod daemon might not be started, has crashed, or failed to start correctly within your WSL2 Ubuntu instance.
  2. Incorrect bindIp Configuration: MongoDB is configured to listen only on localhost (127.0.0.1) within the WSL2 instance, making it inaccessible from the Windows host or other applications trying to connect via the WSL2 instance's external IP address.
  3. Firewall Blocking Connection:
    • WSL2 UFW (Uncomplicated Firewall): If UFW is enabled within your Ubuntu instance, it might be blocking incoming connections to port 27017.
    • Windows Defender Firewall: The Windows firewall might be preventing the Windows host or other applications from communicating with the WSL2 network adapter on port 27017.
  4. WSL2 Network Instability/IP Changes: WSL2 instances typically receive dynamic IP addresses. If your application or configuration is using a hardcoded IP that has changed, or if the WSL2 network stack is in an inconsistent state, connections will fail.
  5. Port Conflict: Another service might already be listening on port 27017 within the WSL2 instance, preventing MongoDB from binding to it. This is less common in a clean setup but worth checking.
  6. Incorrect Application Connection String: The application might be trying to connect to the wrong IP address or port.

Step-by-Step Resolution

Follow these steps meticulously to diagnose and resolve your MongoDB connection issues. Execute all commands related to MongoDB or network configuration within your WSL2 Ubuntu terminal unless explicitly stated otherwise.

1. Verify MongoDB Service Status within WSL2

First, ensure that the mongod service is actually running.

  1. Check Service Status:

    sudo systemctl status mongod
    

    If systemctl is not fully integrated/working in your WSL2 instance, you might need to use service:

    sudo service mongod status
    

    Look for Active: active (running) in the output. If it shows inactive (dead) or any error, proceed to the next steps.

  2. Start MongoDB Service (if stopped):

    sudo systemctl start mongod
    

    Or:

    sudo service mongod start
    
  3. Enable MongoDB to Start on Boot:

    sudo systemctl enable mongod
    

    This ensures MongoDB automatically starts when your WSL2 instance is launched.

If systemctl commands fail or report issues, it might indicate that systemd isn't fully set up or running within your specific WSL2 distribution. Modern Ubuntu WSL2 images often support systemd out-of-the-box, but older setups or custom configurations might require additional steps (e.g., using nohup mongod --fork --logpath /var/log/mongodb/mongod.log for a background process, though this is not recommended for production).

2. Inspect MongoDB Configuration (mongod.conf)

The bindIp setting in MongoDB's configuration file is crucial for network accessibility.

  1. Open Configuration File: The default location for mongod.conf on Ubuntu is /etc/mongod.conf.

    sudo nano /etc/mongod.conf
    
  2. Locate and Modify bindIp: Look for the net: section and specifically the bindIp directive.

    • If you need to connect from within the same WSL2 instance (e.g., an application also running in that Ubuntu instance): bindIp: 127.0.0.1 is usually sufficient and secure.
    • If you need to connect from the Windows host or another WSL2 instance: You need to bind to the WSL2 instance's IP address or all available interfaces.
      • Option A (Recommended for WSL2 cross-connectivity): Find your WSL2's current IP address first (see Step 3) and add it to the bindIp list. Example: If your WSL2 IP is 172.20.128.3, change bindIp: 127.0.0.1 to bindIp: 127.0.0.1,172.20.128.3.
      • Option B (Less Secure, but broadly accessible): Bind to all interfaces by using 0.0.0.0 or ::,0.0.0.0 (for IPv4 and IPv6). Change: bindIp: 127.0.0.1 To: bindIp: 0.0.0.0 (for IPv4 only) Or: bindIp: 0.0.0.0,:: (for both IPv4 and IPv6)

    A typical net section might look like this:

    # network interfaces
    net:
      port: 27017
      bindIp: 127.0.0.1,<YOUR_WSL2_IP> # Example: bindIp: 127.0.0.1,172.20.128.3
      # Or for broader accessibility (less secure without firewall rules):
      # bindIp: 0.0.0.0
    

Binding to 0.0.0.0 makes your MongoDB instance accessible from any network interface, including potentially your local network or even the internet if not properly firewalled. For development, this might be acceptable within a controlled environment, but it is a significant security risk for production systems without strict firewall rules (see Step 3) and authentication (security.authorization: enabled). Always prioritize binding to specific IP addresses.

  1. Save Changes and Restart MongoDB: After modifying mongod.conf, save the file (Ctrl+X, Y, Enter in nano). Then, restart the MongoDB service for changes to take effect:
    sudo systemctl restart mongod
    
    Or:
    sudo service mongod restart
    
    Verify its status again: sudo systemctl status mongod.

3. Check WSL2 IP Address and Windows Firewall

Even if MongoDB is running and correctly bound, the Windows Firewall might be blocking the connection between your Windows host and the WSL2 virtual network adapter.

  1. Get Your WSL2 IP Address: From your WSL2 Ubuntu terminal:

    ip addr show eth0 | grep inet | grep -v inet6 | awk '{print $2}' | cut -d '/' -f 1
    

    This command will output the IPv4 address of your eth0 interface, which is the internal IP address of your WSL2 instance. It typically looks like 172.x.x.x. Note this down.

  2. Configure Windows Defender Firewall: Since WSL2 IPs can change upon restart, it's often more robust to create a firewall rule that allows traffic through the wsl.exe application rather than a specific dynamic IP.

    • Search for "Windows Defender Firewall with Advanced Security" in the Windows Start Menu and open it.
    • In the left pane, click on Inbound Rules.
    • In the right pane, click New Rule….
    • Rule Type: Select Port, then click Next.
    • Protocols and Ports: Select TCP, specify Specific local ports: 27017, then click Next.
    • Action: Select Allow the connection, then click Next.
    • Profile: Ensure all profiles (Domain, Private, Public) are checked (or at least Private for typical home/office development), then click Next.
    • Name: Give it a descriptive name, e.g., WSL2 MongoDB 27017. Click Finish.

    Alternatively, to allow the wsl.exe executable:

    • Follow the above steps until Rule Type. Select Program.
    • Program: Select This program path: and browse to C:WindowsSystem32wsl.exe. Click Next.
    • Action, Profile, Name: Configure as above.

If you are connecting from the Windows host to a WSL2 instance using bindIp: 127.0.0.1 only, you must change the bindIp configuration (Step 2) to include the WSL2 IP or 0.0.0.0 for the Windows host to reach it. The Windows host cannot directly access the 127.0.0.1 of the WSL2 guest.

4. Verify No Port Conflicts (Less Common)

Although less frequent for a fresh MongoDB installation, another process might be using port 27017.

  1. Check for Port Usage in WSL2:

    sudo netstat -tulnp | grep 27017
    

    (You might need to install net-tools: sudo apt update && sudo apt install net-tools)

    If MongoDB is running correctly, you should see an entry like:

    tcp        0      0 0.0.0.0:27017           0.0.0.0:*               LISTEN      <PID>/mongod
    

    If you see a different process's PID listed for 27017, you have a conflict. You would need to stop that process or change MongoDB's port.

  2. Check for Port Usage on Windows (for completeness): Open PowerShell or CMD on Windows:

    netstat -ano | findstr :27017
    

    This checks if any Windows application is using port 27017. While unlikely to directly cause a "connection refused" from WSL2, it could prevent a Windows-based MongoDB from starting, or create confusion.

5. Confirm Application Connection String

Ensure your application's connection string is correctly configured to point to your MongoDB instance.

  • If your application is running within the same WSL2 Ubuntu instance as MongoDB: The connection string should typically be mongodb://127.0.0.1:27017/yourDatabase.
  • If your application is running on the Windows host (e.g., VS Code, another IDE, a Windows-native app): The connection string must use the WSL2 instance's IP address you identified in Step 3. Example: mongodb://<YOUR_WSL2_IP>:27017/yourDatabase (e.g., mongodb://172.20.128.3:27017/yourDatabase).

6. Advanced WSL2 Networking (If Issues Persist)

If you've followed all steps and still face issues, a full WSL2 network reset can sometimes resolve underlying connectivity problems.

  1. Shut Down All WSL2 Instances: Open PowerShell or CMD on Windows and run:

    wsl --shutdown
    

    This will terminate all running WSL2 distributions.

  2. Restart WSL2 and Ubuntu: Simply open your Ubuntu WSL2 terminal again. This will restart the WSL2 virtual machine and assign a new IP address. Repeat Step 3 to get the new WSL2 IP and update any configuration if you hardcoded the IP (or ensure your firewall rules are application-based).

By systematically working through these steps, you should be able to identify and resolve the "MongoDB socket connection failed connection refused port 27017" error, enabling seamless database connectivity for your applications within your Windows WSL2 development environment.

👨‍💻

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.