A crude, but effective solution for hosting local development projects inside WSL 2.
before you start
- node js is required
⚠️ this script changes your host file - save a copy of your host file before use
const { execSync } = require('child_process');
const fs = require('fs');
// Step 1: Get the latest WSL IP address
const wslIpAddress = execSync('wsl hostname -I').toString().trim().split(' ')[0];
// Step 2: Read the Windows host file
const hostFilePath = 'C:/Windows/System32/drivers/etc/hosts';
const hostFileContent = fs.readFileSync(hostFilePath, 'utf8');
const excludeRegex = /docker/;
// Step 3: Update the Windows host file with the latest WSL IP address
const updatedHostFileContent = hostFileContent
.split('\n')
.map(line => line.trim())
.map(line => {
if (excludeRegex.test(line) || line.charAt(0) === '#' || line === '') {
return line;
}
const domain = line.split(/\s+/).slice(-1)[0];
return `${wslIpAddress} ${domain}`;
})
.join('\n');
fs.writeFileSync(hostFilePath, updatedHostFileContent, 'utf8');
Now, you can open up the terminal and use node "C:\wsl\sync-wsl-ip.js
to update all the IP addresses in your windows host file to your current WSL IP address.
In C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup, create a mew shortcut called Sync WSL IP
and set the target to a new file called C:\wsl\sync-wsl-ip.bat
with the following contents.
node "C:\wsl\sync-wsl-ip.bat"
const excludeRegex = /docker|my-windows-only-project/;