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.
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:
- MongoDB Service Not Running: The most common cause. The
mongoddaemon might not be started, has crashed, or failed to start correctly within your WSL2 Ubuntu instance. - Incorrect
bindIpConfiguration: MongoDB is configured to listen only onlocalhost(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. - 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.
- 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.
- 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.
- 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.
Check Service Status:
sudo systemctl status mongodIf
systemctlis not fully integrated/working in your WSL2 instance, you might need to useservice:sudo service mongod statusLook for
Active: active (running)in the output. If it showsinactive (dead)or any error, proceed to the next steps.Start MongoDB Service (if stopped):
sudo systemctl start mongodOr:
sudo service mongod startEnable MongoDB to Start on Boot:
sudo systemctl enable mongodThis ensures MongoDB automatically starts when your WSL2 instance is launched.
If
systemctlcommands fail or report issues, it might indicate thatsystemdisn't fully set up or running within your specific WSL2 distribution. Modern Ubuntu WSL2 images often supportsystemdout-of-the-box, but older setups or custom configurations might require additional steps (e.g., usingnohup mongod --fork --logpath /var/log/mongodb/mongod.logfor 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.
Open Configuration File: The default location for
mongod.confon Ubuntu is/etc/mongod.conf.sudo nano /etc/mongod.confLocate and Modify
bindIp: Look for thenet:section and specifically thebindIpdirective.- 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.1is 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
bindIplist. Example: If your WSL2 IP is172.20.128.3, changebindIp: 127.0.0.1tobindIp: 127.0.0.1,172.20.128.3. - Option B (Less Secure, but broadly accessible): Bind to all interfaces by using
0.0.0.0or::,0.0.0.0(for IPv4 and IPv6). Change:bindIp: 127.0.0.1To:bindIp: 0.0.0.0(for IPv4 only) Or:bindIp: 0.0.0.0,::(for both IPv4 and IPv6)
- Option A (Recommended for WSL2 cross-connectivity): Find your WSL2's current IP address first (see Step 3) and add it to the
A typical
netsection 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- If you need to connect from within the same WSL2 instance (e.g., an application also running in that Ubuntu instance):
Binding to
0.0.0.0makes 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.
- 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:
Or:sudo systemctl restart mongod
Verify its status again:sudo service mongod restartsudo 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.
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 1This command will output the IPv4 address of your
eth0interface, which is the internal IP address of your WSL2 instance. It typically looks like172.x.x.x. Note this down.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.exeapplication 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, specifySpecific 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 leastPrivatefor 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.exeexecutable:- Follow the above steps until Rule Type. Select
Program. - Program: Select
This program path:and browse toC: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.1only, you must change thebindIpconfiguration (Step 2) to include the WSL2 IP or0.0.0.0for the Windows host to reach it. The Windows host cannot directly access the127.0.0.1of 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.
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>/mongodIf 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.
Check for Port Usage on Windows (for completeness): Open PowerShell or CMD on Windows:
netstat -ano | findstr :27017This 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.
Shut Down All WSL2 Instances: Open PowerShell or CMD on Windows and run:
wsl --shutdownThis will terminate all running WSL2 distributions.
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.
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.