How to change the DNS settings for WSL 2
In this article we will go thorough a step-by-step guide to help you change the automatic DNS resolution in WSL 2. This is usually needed when you run WSL 2 behind a VPN.
First, we need to turn off auto generation of /etc/resolv.conf to setup our custom DNS servers.
We'll do it by editing /etc/wsl.conf and setting generateResolvConf to false.
echo "[network]" | sudo tee /etc/wsl.conf echo "generateResolvConf = false" | sudo tee -a /etc/wsl.conf
Now, we enable editing the /etc/resolv.conf file
sudo chattr -i /etc/resolv.conf
and after that, we delete the current auto generated one.
sudo rm -rf /etc/resolv.conf
Now, we can setup our custom DNS servers. For the purpose of this article, I'm going to setup Google's DNS servers, you can always add more/other servers.
echo "nameserver 188.8.131.52" | sudo tee /etc/resolv.conf echo "nameserver 184.108.40.206" | sudo tee -a /etc/resolv.conf
Finally, we lock /etc/resolv.conf from editing
sudo chattr +i /etc/resolv.conf
Close and reopen the terminal, and your configured DNS settings will have effect.