Skip to content

Instantly share code, notes, and snippets.

@djfdyuruiry
Last active May 19, 2022 20:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save djfdyuruiry/8ec94d6454fbacccafb092022fe041a3 to your computer and use it in GitHub Desktop.
Save djfdyuruiry/8ec94d6454fbacccafb092022fe041a3 to your computer and use it in GitHub Desktop.
WSL 2 - Fix DNS Issues

Fix DNS Issues in WSL 2

This guide will help overcome the DNS issues present in WSL 2 while still making the Windows host IP autogenerated by WSL available for use. Note: this was tested on Windows 10 Build 2004, running Ubuntu 20.04 LTS in WSL 2.

  • Open a WSL terminal

  • Copy the contents of configure-wsl-dns.sh to /opt/configure-wsl-dns.sh:

    sudo nano /opt/configure-wsl-dns.sh
  • Make it executable:

    sudo chmod +x /opt/configure-wsl-dns.sh
  • Add a passwordless sudo entry in the file /etc/sudoers.d/configure-wsl-dns:

    %admin ALL = (root) NOPASSWD: /opt/configure-wsl-dns.sh
    
  • Update ~/.zshrc or ~/.bashrc:

    # WSL networking
    sudo /opt/configure-wsl-dns.sh
    
    export $(</etc/wsl-host.env)
    
    # The env var 'WSL_HOST' is now available which
    # contains the IP of the host machine if you need
    # it for XServer setup etc.
  • Exit and then go back into your WSL terminal

#! /usr/bin/env bash
set -e
resolvConfPath="/etc/resolv.conf"
resolvConfDirPath="/etc/resolvconf/resolv.conf.d"
resolvHeadConfPath="${resolvConfDirPath}/head"
wslHostEnvPath="/etc/wsl-host.env"
function writeResolvConf() {
cat > "$1" <<- EOM
## Change the below as you see fit
# cloudflare
nameserver 1.1.1.1
# google
nameserver 8.8.8.8
# local
nameserver 192.168.0.1
EOM
}
function saveWslHostConfig() {
rm -f "${wslHostEnvPath}"
local wslHost=$(cat "${resolvConfPath}" | grep -v '#' | cut -d ' ' -f 2)
printf "WSL_HOST=${wslHost}" > "${wslHostEnvPath}"
}
function main() {
# exit if resolv.conf has already been patched
grep 'generated by WSL' /etc/resolv.conf > /dev/null || exit 0
saveWslHostConfig
writeResolvConf "${resolvConfPath}"
# if systemd is enabled - you will need this
mkdir -p "${resolvConfDirPath}"
writeResolvConf "${resolvHeadConfPath}"
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment