Accessing WSL 2 Web Services on a Windows 11 PC
Windows Subsystem for Linux version 2 (WSL 2) is a significant improvement over its predecessor, providing a full Linux kernel and better performance for running Linux applications on Windows. One common use case is to run web services on WSL 2 and access them from the Windows host or other devices on the network. However, it can be a complex scenario to set up and access these web services.
Prerequisites
Before we dive into the details, make sure you have the following prerequisites:
- A Windows 11 PC with WSL 2 enabled
- A Linux distribution installed on WSL 2 (e.g., Ubuntu, Debian, etc.)
- A web service running on the Linux distribution (e.g., Nginx, Apache, etc.)
Accessing Web Services on the Windows Host
To access a web service running on WSL 2 from the Windows host, you need to use the localhost IP address (127.0.0.1) and the port number the web service is running on. For example, if you have Nginx running on WSL 2 on port 80, you can access it from the Windows host using the following URL:
http://127.0.0.1However, this may not always work due to network configuration issues. In that case, you can use the WSL 2 IP address instead of localhost. To find the WSL 2 IP address, run the following command on the Windows command prompt:
wsl --ipThis will display the IP address of the WSL 2 distribution. Use this IP address and the port number to access the web service from the Windows host.
Accessing Web Services from Other Devices
To access a web service running on WSL 2 from other devices on the network, you need to use the WSL 2 IP address and the port number. However, by default, WSL 2 does not allow incoming connections from other devices. To enable incoming connections, you need to modify the WSL 2 network configuration.
First, run the following command on the Windows command prompt to stop the WSL 2 distribution:
wsl --shutdownThen, open the Windows Terminal as an administrator and run the following command to modify the network configuration:
New-NetNat -Name WSL -InternalIPInterfaceAddressPrefix "192.168.0.0/16" -Type V4This command creates a new NAT network for WSL 2 with the IP address range of 192.168.0.0/16. Make sure to replace this range with the IP address range of your network.
Next, run the following command to get the WSL 2 distribution's IP address:
wsl --ipThis command will display the IP address of the WSL 2 distribution. Use this IP address and the port number to access the web service from other devices on the network.
Accessing web services running on WSL 2 from a Windows 11 PC or other devices on the network can be a complex scenario. However, by following the steps outlined in this article, you can successfully access web services running on WSL 2.