Introduction
I will guide you through this process of how to connect Windows Subsystem for Linux (WSL) to MongoDB running on a Windows machine.
Step 1: Verify MongoDB is Running on Windows
Before attempting to connect, ensure MongoDB is actively running on your Windows machine. This can be checked using MongoDB’s command-line tools or the services management interface in Windows.
Step 2: Identify Your Windows IP Address
To connect from WSL to MongoDB on Windows, you need the IP address of your Windows machine. Open Command Prompt and type ipconfig to find the 'IPv4 Address' under your network adapter. This IP is what WSL will use for the connection.
Step 3: Configure MongoDB to Accept Remote Connections
By default, MongoDB is configured to bind to localhost. To connect from WSL, modify the MongoDB configuration:
Open
mongod.cfg
, typically found inC:\Program Files\MongoDB\Server\[version]\bin\
.Locate the
net
section in themongod.cfg
and changebindIp
from127.0.0.1
to0.0.0.0.
This change allows connections from any IP address.Restart MongoDB to apply the changes.
Note: Allowing connections from all IPs can be a security risk. Ensure you’re operating in a secure network.
Step 4: Adjust Windows Firewall Settings
For WSL to communicate with MongoDB, the MongoDB port (default is 27017) must be open on your Windows Firewall:
- Navigate to ‘Windows Defender Firewall’ -> ‘Advanced Settings’.
- Create a new ‘Inbound Rule’ to allow TCP traffic on port 27017.
Step 5: Connect from WSL
With MongoDB configured and the firewall adjusted, you can now connect from your project in WSL using the new connection string:
mongodb://192.168.18.2:27017/your_database_name // replace your local ip with the <Windows-IP>
Replace with your actual Windows IP address.
Step 6: Troubleshooting Tips
If you encounter issues, here are some troubleshooting steps:
- Ensure MongoDB is running on Windows.
- Confirm that port 27017 is open and listening.
- Check for network connectivity issues between WSL and Windows.
- Verify the accuracy of the IP address and port number.
Conclusion
Integrating MongoDB with WSL can streamline your development process, especially if you are juggling between Linux and Windows environments. By following these steps, you can establish a secure and efficient connection, enhancing your productivity and workflow.
For more insights and tech tips, stay tuned!
Chomba, Senior Software Engineer, BongoHive Consult
Disclaimer: This article is intended for educational / development environment purposes only. Configuring network and database settings can expose your system to security risks. Always ensure best practices in network security, especially in production environments.
Top comments (0)