Accessing Hyper-V Virtual Machines with WSL2 Web Server
As a novice in Hyper-V and WSL2, you might be interested in setting up a web server on WSL2 to make it accessible to local virtual machines. This article will guide you through the process, specifically focusing on the WSL2's mirrored network mechanism.
What is Hyper-V and WSL2?
Hyper-V is a native hypervisor from Microsoft that creates virtual machines on x86-64 systems. On the other hand, WSL2 (Windows Subsystem for Linux, version 2) is a compatibility layer for running Linux binary executables natively on Windows 10. WSL2 utilizes a real Linux kernel, which greatly improves its performance and functionality compared to WSL1.
Enabling WSL2 and Hyper-V
To get started, first ensure that Virtual Machine Platform, Windows Subsystem for Linux, and Hyper-V features are enabled in Windows 10. This can be done through the "Turn Windows features on or off" settings page.
Setting up a Web Server on WSL2
First, install your preferred Linux distribution (e.g., Ubuntu) from the Microsoft Store. Once installed, launch it, update the package lists, and install a web server like Apache or Nginx:
sudo apt update
sudo apt install apache2
Accessing the Web Server from Hyper-V Virtual Machines
By default, the WSL2 network is NAT-configured, meaning that the WSL2 machines aren't directly accessible by Hyper-V virtual machines. To enable access, configure a mirrored network on Hyper-V virtual machines:
- Shut down your Hyper-V virtual machine.
- Open the Settings for the virtual machine, then navigate to the "Network Adapter" settings.
- Under "Virtual Switch", select "New virtual network switch", then choose "External".
- Select the physical network adapter and check "Allow management operating system to share this network adapter".
- Click "Apply" and "OK".
- Now, edit the WSL2 network configuration:
netsh interface ipv4 set subinterface "vEthernet (WSL)" mtu=1500 store=persistent
Replace "vEthernet (WSL)" with the name of the virtual switch you created in Hyper-V. After that, ensure that both WSL2 and the Hyper-V virtual machine are using the same virtual switch.
IP Addressing and Accessing the Web Server
Now, you need to figure out the IP address of the WSL2 environment:
ip a
Look for the IP address assigned to the eth0 network interface. With this IP address, you can access the web server from the Hyper-V virtual machine using a web browser or tools like curl.
This article provided a step-by-step guide on setting up a web server on WSL2 and allowing access to it from Hyper-V virtual machines. Key steps included enabling WSL2 and Hyper-V, setting up a web server, and configuring a mirrored network for access.