Quick guide to connect MongoDB on Windows from WSL2.
Table of contents
Open Table of contents
Introduction
Recently, I encountered an issue connecting to MongoDB running on Windows from WSL2 (Windows Subsystem for Linux). Being new to the Windows and WSL ecosystem after using Apple machines for 15 years, I spent about 4 hours troubleshooting. After diving through various online threads, I managed to resolve the issue using the following steps.
Steps
Stop the MongoDB Service
- Stop the
MongoDBservice from WindowsServices.
Locate MongoDB configuration file
- Locate
mongod.cfgconfig file usingFile Explorer.
Typically it’s found at C:\Program Files\MongoDB\Server\8.0\bin. Replace 8.0 with your installed MongoDB version.
Edit mongod.cfg file
- Open command prompt with
Administratorprivilages andcdinto the directory wheremongod.cfgfile is located. - Run
notepad mongod.cfgto open file in Notepad. - Update
bindIpparameter from
bindIp: 127.0.0.1
to
bindIp: 0.0.0.0
Allow MongoDB through Windows Firewall
- Search for
Allow an app through Windows Firewallin the Windows search bar. - Click
Change settingson top right corner. - Click
Allow another app...button at the bottom right. - Click
Browseto locate and select themongod.exe. - Click
Network typesand ensure bothprivateandpublicnetwork types are selected. - Click
Addto create a set of inbound rules for MongoDB in the Windows Defender Firewall.
Restart the MongoDB service
- Go back to
Servicesand start theMongoDBservice.
Find your Windows host IPv4 address
- Run
ipconfigcommand in your command prompt. - Note the IPv4 address under the active network adapter (e.g., 192.168.x.x)
Update MongoDB URI in WSL2
- Use the noted IPv4 address to modify your MongoDB connection URI in WSL2. For example
mongodb://<your-host-ipv4-address>:27017/<your-db-name>
Conclusion
By following these steps, I successfully connected to a local MongoDB instance running on Windows from my Serverless API project running inside WSL2. 🎉