how to reach http server running on wsl2 from windows host
- User
how to reach http server running on wsl2 from windows host
- Assistant
Reaching an HTTP server running on WSL2 (Windows Subsystem for Linux version 2) from the Windows host system is straightforward, but it requires understanding how networking is set up in WSL2. Unlike WSL1, which had a more integrated networking setup with Windows, WSL2 runs in a lightweight VM and has a separate network bridge. As of my last update in April 2023, follow these steps to access your HTTP server running in WSL2 from your Windows host:
1. Find the IP Address of Your WSL2 Instance
First, you need to find out the IP address that WSL2 is using. To do this:
- Open a WSL2 terminal.
- Run the command
ip addrorifconfig. - Look for the
inetaddress under an interface that is notlocalhost. This is usually undereth0. The address might look something like192.168.x.x.
2. Access the HTTP Server
Assuming the HTTP server in WSL2 is running on port 8000 and the IP address you found was
192.168.100.4, you can access the server from your Windows host by navigating tohttp://192.168.100.4:8000in your web browser.3. Making it More Convenient with /etc/hosts (Optional)
Constantly keeping track of the WSL2 IP address can be cumbersome since it can change every time WSL2 starts up. One way to make this easier, albeit with some manual steps required if the IP changes, is to edit the
hostsfile on your Windows system to include a static hostname for your WSL2 IP address.- Open Notepad as Administrator (required to save changes to the hosts file).
- Open the file
C:\Windows\System32\drivers\etc\hosts. - Add a line like
192.168.100.4 wsl.myserver. Save the changes. - Now, you can access your server using
http://wsl.myserver:8000from your Windows browser.
4. Using Port Forwarding (Alternative Method)
If you want to avoid dealing with dynamic IP addresses, you can use port forwarding. This requires setting up a script or a service inside WSL2 to forward ports to the Windows host. Here's a simple example using
socat(you may need to install it first):- Run the command
sudo socat TCP-LISTEN:8000,fork TCP:127.0.0.1:8000inside WSL2. - This command listens on port 8000 on all interfaces of the WSL2 and forwards incoming connections to localhost:8000 of the WSL2 environment.
Replace
8000with whatever port your HTTP server is using. Note that with this approach, you can access your server vialocalhost:8000or127.0.0.1:8000on your Windows system.Note
Microsoft is continually updating WSL2, and there could be newer, more integrated solutions for networking between WSL2 and Windows in the future. Always check the official WSL documentation or the Windows blog for the latest features and enhancements.