(I've provided a simple working solution in response)
I recently moved from macOS to WSL 2. I have two node servers running within WSL 2 (Ubuntu distro). Each must be accessible through a custom hostname for development vs production purposes. I've had difficulty accessing the node servers via custom hostnames (ie set in some ../etc/hosts file) especially given WSL 2's dynamic IP that changes per WSL/pc 'boot'. How does one go about setting custom hostnames in WSL 2?
Scenario:
Each node.js app server (again running within WSL 2) must be accessed from the browser with the following urls/custom hostnames:
After searching around I have found the following relatively simple process works. I thought I'd share and save some time and headache for those new to WSL 2. Note, although I'm using node as the server stack, this process should more or less be the same for other app/web server stacks.
Note the following SE post is the basis of the solution. It's also worthwhile to examine MSFT's reference on WSL vs WSL 2. Also note, I haven't provided deep rationale on why these steps are required, why we might need custom hostnames, ipv6 options in ../etc/hosts, the meaning of 127.0.0.1, loopback addresses, WSL 2 and distro management, etc. These are subjects beyond the scope of this post.
Simple scenario:
Each node.js app server (again running within wsl 2) can be accessed from the browser with the following urls:
Two key items:
127.0.0.1 localhost 127.0.0.1 www.app1.com 127.0.0.1 www.app2.com 255.255.255.255 broadcasthost ::1 localhost www.app1.com www.app2.com
[wsl2] localhostForwarding=true
- Note: there's a reference to this in WSL 2 Ubuntu distro's /etc/hosts.
- Also note, this requires WSL shutdown and reboot. Shutting down your terminal is insufficient. Also total machine boot is not required. Simply run:
wsl --shutdown (in Powershell) or wsl.exe --shutdown (within Ubuntu)
Then restart the Windows Terminal app (or any WSL terminal) to access the updated WSL 2 environment. The apps with custom urls/hostnames will now work in the browser permanently and WSL 2's dynamic IP is circumvented.