WSL2 vhost IP address

Viewed 1280

I have set up WSL2 with Ubuntu 20.04 and use it for web development. On WSL2 I have installed a LAMP stack.

I have set up some vhosts with apache in WSL2. So far it is working fine. But what I find annoying is that I have to set every day the new IP that I get for WSL in the Windows hosts file.

I have tried to set a static IP in Ubuntu, but I am not quite sure if it is the right way and if it is working. I have created in the /etc/netplan folder a file with an IP. Mainly I followed this advice. I have set an IP address but I get an error when I do sudo netplan apply.

I have also tried this approach and wrote a PowerShell script. But I don't know how this should set the IP.

I would be happy and grateful for any suggestions.

1 Answers

Do you really need the IP address for your use-case?

WSL2 has a feature called localhostForwarding that should be enabled by default. This should allow you to directly access services running inside the WSL2 instance simply by using localhost from within Windows.

With nothing else running in WSL, try the following from the shell:

python3 -m http.server 8088

And see if you can access it from your Windows browser at localhost:8088.

If this doesn't work, then you may have run into a WSL bug where localhostForwarding breaks when hibernating, or when Fast Startup is enabled in Windows (it is the default). If that's the case, try running the following in PowerShell:

wsl --shutdown

Then restart and try it again.

Then in your C:\Windows\System32\drivers\etc\hosts, set your vhost names to 127.0.0.1 and ::1.

Related