Connect MongoDB Compass (Windows) to WSL2 mongod server

After being able to start mongod server and mongo shell in WSL2, I wish to use MongoDB Compass installed on Windows to connect with the mongod server in WSL2. However I haven’t been able to do so. I tried to connect with URI “mongodb://localhost:27017” in Compass after starting mongod in WSL2 at port 27017, but the attempt was not successful. This is surprising because WSL2 supports local host forwarding (i.e., 127.0.0.1 on WSL2 is the same 127.0.0.1 on Windows).

Any suggestion will be appreciated. Thanks!

Check these links.May help

Thanks Ramachandra. Unfortunately, all methods in the first link did not work (e.g. I tried wsl --shutdown and disabling fast startup), and the second link answered the opposite of my question (connect to Windows MongoDB from WSL).

As a guess, is the issue related to how mongodb protocol is configured? For example, If I run python -m http.server --bind 127.0.0.1 8000 in WSL and visit “http://127.0.0.1:8000” in Firefox on Windows, everything works. I can say that localhost forwarding of WSL works for HTTP protocol. Is it possible that MongoDB network protocol does have the same support?

After much tweaking, I found a workaround but it may have security risk. I would appreciate if anyone could recognize the risk and recommend a better solution.

Step 1: (in WSL2) Start mongod but bind to all IP, not just localhost

$ mongod --bind-ip-all

Step 2: (in WSL2) Find the IP address of WSL2

$ ip addr | grep eth0 

Copy the IP address right after “inet”. For example, if the result returns “inet 162.38.25.44/20 brd 162.38.30.255 scope global eth0”, then the IP address is 162.38.25.44.

Step 3: (in Windows) Suppose my WSL2 IP address is 162.38.25.44, then run MongoDB compass and connect to the address “mongodb://162.38.25.44:27017”

What I don’t understand is why the first step requires binding to all IP, while binding to just localhost or 127.0.0.1 will not work. Any suggestions?

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.