Skip to content

Instantly share code, notes, and snippets.

@coltenkrauter
Last active May 17, 2024 04:53
Show Gist options
  • Save coltenkrauter/608cfe02319ce60facd76373249b8ca6 to your computer and use it in GitHub Desktop.
Save coltenkrauter/608cfe02319ce60facd76373249b8ca6 to your computer and use it in GitHub Desktop.
Fix DNS resolution in WSL2
More recent resolution:
1. cd ~/../../etc (go to etc folder in WSL).
2. echo "[network]" | sudo tee wsl.conf (Create wsl.conf file and add the first line).
3. echo "generateResolvConf = false" | sudo tee -a wsl.conf (Append wsl.conf the next line).
4. wsl --terminate Debian (Terminate WSL in Windows cmd, in case is Ubuntu not Debian).
5. cd ~/../../etc (go to etc folder in WSL).
6. sudo rm -Rf resolv.conf (Delete the resolv.conf file).
7. In windows cmd, ps or terminal with the vpn connected do: Get-NetIPInterface or ipconfig /all for get the dns primary and
secondary.
8. With the dns primary and secondary getted replace the numbers in the next step in the X.X.X.X
9. echo "nameserver X.X.X.X" | sudo tee resolv.conf (Create resolv.conf and append the line.)
10. echo "nameserver X.X.X.X" | sudo tee -a resolv.conf (Append the line in resolv.conf)
11. wsl --terminate Debian (Terminate WSL in Windows cmd, in case is Ubuntu not Debian).
12. sudo chattr +i resolv.conf
13. And finally in windows cmd, ps or terminal:
Get-NetAdapter | Where-Object {$_.InterfaceDescription -Match "Cisco AnyConnect"} | Set-NetIPInterface -InterfaceMetric 6000
Credit: @MartinCaccia, @yukosgiti, @machuu and @AlbesK:
https://github.com/microsoft/WSL/issues/4277
https://github.com/microsoft/WSL/issues/4246
---
Original resoltuion:
1. Create a file: /etc/wsl.conf.
2. Put the following lines in the file in order to ensure the your DNS changes do not get blown away
[network]
generateResolvConf = false
3. In a cmd window, run wsl --shutdown
4. Restart WSL2
5. Create a file: /etc/resolv.conf. If it exists, replace existing one with this new file.
6. Put the following line in the file
nameserver 8.8.8.8 # Or use your DNS server instead of 8.8.8.8 which is a Google DNS server
7. Repeat step 3 and 4. You will see git working fine now.
Credit: https://github.com/microsoft/WSL/issues/4285#issuecomment-522201021
@thomasfrobieter
Copy link

If you need to change it again afterwards you'll get:

rm: cannot remove 'resolv.conf': Operation not permitted

Fix it by:

  1. lsattr /etc/resolv.conf
  2. sudo chattr -i /etc/resolv.conf
  3. lsattr /etc/resolv.conf

(https://support.tools/post/fix-stuck-resolv-conf/)

@sabotagebeats
Copy link

At the step 5 : Error writing /etc/resolv.conf: No such file or directory
I don't understand why I'm getting this error

are you using sudo?

This solution stops working after I reboot. Anyone else face the same issue? The resolv.conf is still present, the wsl.conf file is still present as well.

I also have this issue however for me the resolv.conf disappears on each reboot and the steps need to be done again.

@cameroncuster
Copy link

This saved me lots of time, I appreciate your efforts.

@xXGoziXx
Copy link

I have to enter this command in powershell/cmd everything I connect to the VPN (Get-NetAdapter | Where-Object {$_.InterfaceDescription -Match "Cisco AnyConnect"} | Set-NetIPInterface -InterfaceMetric 6000)
Is there any workaround for this. Like maybe on connecting to VPN run above command?

@Pabosik
Copy link

Pabosik commented Jul 22, 2021

So first of all: THANK YOU SO VERY MUCH! This issue has been plaguing me for I dunno how long... I even tried the Cisco Anyconnect from Windows Store, and that works, but it keeps dropping connections, glitching, bugging out, plus it really doesn't work all that well in combination with WSL2 and vscode... basically, vscode tries to connect to it, but since the routes are changed somehow, it can't reach, so it takes 300s to timeout and only starts afterwards... horrible.

Aaanyways - I prepared a little powershell script so that you dont have to run step 13:
Get-NetAdapter | Where-Object {$_.InterfaceDescription -Match "Cisco AnyConnect"} | Set-NetIPInterface -InterfaceMetric 6000
manually every time you connect to VPN. Keep in mind that I assume you've completed the 13 steps in the original post and that the DNS is working for you. This just helps simplify the procedure a bit.

This is the script - very simple - lets call it vpn-connect.ps1:

cd 'C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client'; ./vpncli.exe connect <insert-vpn-address-here>
Get-NetAdapter | Where-Object {$_.InterfaceDescription -Match "Cisco AnyConnect"} | Set-NetIPInterface -InterfaceMetric 6000

Now I thought that it would be nice if I could just click a shortcut and run the script as admin. You can do that by creating a shortcut with this executable:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy unrestricted -file <insert-path-to-powershell-script>\vpn-connect.ps1

Now after you've created the shortcut, the last thing you need to do is to right-click it, go to properties, click 'Shortcut' on top, and then 'Advanced' and there tick 'Run as administrator'.

That's it. I can now connect to VPN via cisco by a single double click (I still have to fill in the password though) and the DNS resolving works inside WSL2. Even my vscode now starts instantly when on VPN... pure awesomeness.

Hope this helps someone.

@hareeshghk
Copy link

Thank you

@ajpfoster
Copy link

Yikes finally sorted this by after following a lot of similar issues.

My install is on work laptop so behind Cisco AnyConnect and Umbrella Roaming firewalls but no issues there.

I downgraded to WSL 1 which was grabbing the correct loopbacks in the resolv.conf

Copied these to notepad.

Upgraded to WSL2

Created the resolv.conf file with these exact addresses (not the symlink)

Created /etc/wsl.conf with generateResolvConf = false

Restarted WSL and I have DNS again.

Yay! For now

@smartgokul
Copy link

Thank you for the info, This is more help full for me to resolve the connection issues in WSL on windows 10. 👍

@dividy
Copy link

dividy commented Sep 2, 2021

Thanks!

@dragonro
Copy link

Thanks, great tip!

@Rico-la
Copy link

Rico-la commented Sep 17, 2021

Thanks, great tip. I finally resolve my problem dns in WSL ! 👍

@MatMercer
Copy link

MatMercer commented Sep 20, 2021

Thx for sharing the fix!
I created a script here to automate the process:

https://gist.github.com/MatMercer/f7e25b9c8ce7ca40dd3b220346136d23

@jimboowens
Copy link

I use Docker Desktop with WSL2, and the IPv4 nameserver had to also be in the resolv.conf as defined in the ipconfig /all result in order to work. Adding that back in resolved (pun intended) the problem.

@Lushiane
Copy link

I couldn't solve my problem with the steps given. :(

@rubin55
Copy link

rubin55 commented Sep 27, 2021

Just a note to tell readers here I wrote a nice fix for this that is quite a bit simpler + less error-prone than some of the solutions I've found floating around, using Windows Task Scheduler. In short, it's a powershell script that can write a correct resolv.conf based on InterfaceMetric order (so just make sure your VPN adapter has a lower (which means higher priority) InterfaceMetric than your WiFi or Ethernet card - meaning, you have control over where a nameserver line ends up, above or below). Have a look here:

microsoft/WSL#2884 (comment)

@paradonym
Copy link

paradonym commented Oct 31, 2021

so in short the resolution above is to write active nameservers into resolv.conf?
So simply writing some public nameservers into that file already helps?

@BtbN
Copy link

BtbN commented Oct 31, 2021

That's hardly the resolution. It's a workaround.
A clean Windows reinstall fixed the whole issue for me.

@paradonym
Copy link

That's hardly the resolution. It's a workaround. A clean Windows reinstall fixed the whole issue for me.

It's almost a fresh install of windows 11 for me, because I switched to a cpu with fTPM for it.
Always when I use a vpn WSL is offline, when I don't use it everything's fine. Just like windows doesn't updates WSL on every network adapter switch.

@sascha-andres
Copy link

If, even as root you cannot change /etc/resolveconf try looking if it is immutable (lsattr /etc/resolv.conf) and probably remove it

@mlemnian
Copy link

to remove the immutability just type:
sudo chattr -i /etc/resolv.conf

@wbern
Copy link

wbern commented Nov 22, 2021

To anyone with Pulse Secure VPN issues, this helped me (although I had to set MTU to 1326.)

microsoft/WSL#4698 (comment)

I ran sudo ip link set dev eth0 mtu 1326, that was the MTU required to make sudo apt update and curl www.google.com work for me.

@ChrisKader
Copy link

My issue seemed to be related to Trend Micro. I disabled the "Trend Micro Lightweight Filter Driver" and that seemed to resolve my issue. After 6 hours of trial and error by looking at 100 other WSL github issues.

image

@santiagocasas
Copy link

Thanks bro!
This worked for me using Cisco VPN after opening the WSL bash in Windows.

With your latest command I got:

`Set-NetIPInterface : Access is denied.
At line:1 char:85

  • ... -Match "Cisco AnyConnect"} | Set-NetIPInterface -InterfaceMetric 6000
  •                              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : PermissionDenied: (MSFT_NetIPInter...ystemName = ""):ROOT/StandardCimv2/MSFT_NetIPInterf
      ace) [Set-NetIPInterface], CimException
    • FullyQualifiedErrorId : Windows System Error 5,Set-NetIPInterface

Set-NetIPInterface : Access is denied.
At line:1 char:85

  • ... -Match "Cisco AnyConnect"} | Set-NetIPInterface -InterfaceMetric 6000
  •                              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : PermissionDenied: (MSFT_NetIPInter...ystemName = ""):ROOT/StandardCimv2/MSFT_NetIPInterf
      ace) [Set-NetIPInterface], CimException
    • FullyQualifiedErrorId : Windows System Error 5,Set-NetIPInterface`

and still it worked

@OmriSama
Copy link

OmriSama commented Dec 2, 2021

Does anyone know why setting the Interface Metric to 6000 made it work?

@beedle-
Copy link

beedle- commented Dec 3, 2021

Between 11 and 12 this step is missing:
cd ~/../../etc (go to etc folder in WSL).

For 13., it can only be executed in Powershell

@mlemnian
Copy link

mlemnian commented Dec 3, 2021

My take on this would be:

Within WSL:

  1. echo "[network]" | sudo tee /etc/wsl.conf (Create /etc/wsl.conf file and add the first line).
  2. echo "generateResolvConf = false" | sudo tee -a wsl.conf (Append the next line to /etc/wsl.conf).

Within cmd or powershell:

  1. wsl --terminate Debian (Terminate WSL in Windows cmd, in case is Ubuntu not Debian).

Within WSL:

  1. sudo rm -Rf /etc/resolv.conf (Delete the /etc/resolv.conf file).

Within cmd or powershell:

  1. wsl --terminate Debian (Terminate WSL in Windows cmd, in case is Ubuntu not Debian).
  2. Get-NetIPInterface or ipconfig /all to get the primary and secondary DNS entries.

Within WSL:

  1. With the primary and secondary dns returned in step 6, replace the IP numbers in the next step in the X.X.X.X
  2. echo "nameserver X.X.X.X" | sudo tee /etc/resolv.conf (Create /etc/resolv.conf and append the line.)
  3. echo "nameserver X.X.X.X" | sudo tee -a /etc/resolv.conf (Append the line in /etc/resolv.conf)

Within cmd or powershell:

  1. wsl --terminate Debian (Terminate WSL in Windows cmd, in case is Ubuntu not Debian).

Within WSL:

  1. sudo chattr +i /etc/resolv.conf (Make /etc/resolve.conf immutable)

Within the powershell:

  1. Get-NetAdapter | Where-Object {$_.InterfaceDescription -Match "Cisco AnyConnect"} | Set-NetIPInterface -InterfaceMetric 6000

Credit: @MartinCaccia, @yukosgiti, @machuu and @AlbesK:
microsoft/WSL#4277
microsoft/WSL#4246

@BKDAmaughan
Copy link

Is there a way to make the local host respond with DNS so we don't have to remove the autoconfig.

@BtbN
Copy link

BtbN commented Dec 3, 2021

That's how WSL works by default, and precisely what's broken for some people.
I eventually gave up and reinstalled the whole PC. Then the local WSL DNS resolver worked fine again, even with AnyConnect VPN and everything.

@BKDAmaughan
Copy link

BKDAmaughan commented Dec 3, 2021 via email

@the-last-byte
Copy link

Amazing! Cheers!

@mlclmtan
Copy link

I followed below, and it's working with my WSL2 Ubuntu, CiscoAnyConnect! Thank you.

  1. cd ~/../../etc (go to etc folder in WSL).
  2. echo "[network]" | sudo tee wsl.conf (Create wsl.conf file and add the first line).
  3. echo "generateResolvConf = false" | sudo tee -a wsl.conf (Append wsl.conf the next line).
  4. wsl --terminate Debian (Terminate WSL in Windows cmd, in case is Ubuntu not Debian).
  5. cd ~/../../etc (go to etc folder in WSL).
  6. sudo rm -Rf resolv.conf (Delete the resolv.conf file).
  7. In windows cmd, ps or terminal with the vpn connected do: Get-NetIPInterface or ipconfig /all for get the dns primary and
    secondary.
  8. With the dns primary and secondary getted replace the numbers in the next step in the X.X.X.X
  9. echo "nameserver X.X.X.X" | sudo tee resolv.conf (Create resolv.conf and append the line.)
  10. echo "nameserver X.X.X.X" | sudo tee -a resolv.conf (Append the line in resolv.conf)
  11. wsl --terminate Debian (Terminate WSL in Windows cmd, in case is Ubuntu not Debian).
  12. sudo chattr +i resolv.conf
  13. And finally in windows cmd, ps or terminal:
    Get-NetAdapter | Where-Object {$_.InterfaceDescription -Match "Cisco AnyConnect"} | Set-NetIPInterface -InterfaceMetric 6000

@S4lem
Copy link

S4lem commented Dec 20, 2021

I also have a corporate Cisco AnyConnect VPN and I encountered this problem. After hours of researches for a fix, I had to :

  • edit /etc/resolv.conf and /etc/wsl.conf files (as described previously)

  • switch back to WSL 1.

And my DNS problem was fixed.

@N3RDIUM
Copy link

N3RDIUM commented Jan 4, 2022

Thanks for the help! You saved my day.

@leon-sleepinglion
Copy link

Saved my day, cheers!

@damasiormoura
Copy link

Thanks a lot!!!!!

@IzStriker
Copy link

Worked very well, thank you!

@kalihman
Copy link

This worked for me. You saved my day sir 👍

@garfieldchou
Copy link

Thank you very much!

@janovesk
Copy link

I would be skeptical of any solutions that involve setting the VPN virtual adapter InterfaceMetric to a high value, like 6000.

By doing this, you force all your network traffic to use any other route, in practice avoiding the VPN altogether. If that is an acceptable solution, why not just turn off the VPN to prevent the issue in the first place?

This solution will also not work if you need to access a resource only available through the VPN.

I wrote about the issue in detail and a better fix here: https://janovesk.com/wsl/2022/01/21/wsl2-and-vpn-routing.html

@ChrisKader
Copy link

ChrisKader commented Jan 25, 2022 via email

@tutods
Copy link

tutods commented Jan 28, 2022

@MatMercer i try you script but appears error on powershe.exe
Can help me?

@ten0s
Copy link

ten0s commented Feb 1, 2022

I found that one of my VPN blocks DNS queries to 8.8.8.8.
By default DNS uses UDP. My solution is to force DNS to use TCP instead.

The below configs work with and without VPN.

$ cat /etc/wsl.conf
[network]
generateResolvConf = false
$ cat /etc/resolv.conf
options use-vc
nameserver 8.8.8.8

@m2hd1
Copy link

m2hd1 commented Feb 1, 2022

$ cat /etc/resolv.conf
options use-vc
nameserver 8.8.8.8

@ten0s thank you !!! that fixed the issue for me
I've been looking for a simple solution like this one for a while

@tutods
Copy link

tutods commented Feb 1, 2022

@ten0s you are using WSL2 or WSL1?
For me only working change from WSL2 to WSL1

@ten0s
Copy link

ten0s commented Feb 1, 2022

@tutods WSL2

@tutods
Copy link

tutods commented Feb 1, 2022

So strange. Already try a lot of things and nothing works

@m2hd1
Copy link

m2hd1 commented Feb 1, 2022

@ten0s for some reasons the /etc/resolv.conf gets wiped out (or probably overwritten) after rebooting my machine

although I did check I still had in my /etc/wsl.conf file

[network]
generateResolvConf = false

is there a clean way to force it to always have your recommended resolv.conf settings ?

@mlemnian
Copy link

mlemnian commented Feb 1, 2022

@m2hd1
You need to modify the /etc/wsl.conf file
(within your WSL) like that:

echo "[network]" | sudo tee /etc/wsl.conf
echo "generateResolvConf = false" | sudo tee -a /etc/wsl.conf

@ten0s
Copy link

ten0s commented Feb 1, 2022

@m2hd1, you need to unsure that your Linux is really restarted.

In Windows terminal

Shutdown all

wsl --shutdown

Check

wsl --list -v

Your Linux should be Stopped

Start it again and then check /etc/resolv.conf

@m2hd1
Copy link

m2hd1 commented Feb 1, 2022

@ten0s I tried your steps but the /etc/resolv.conf keeps disappearing after shuting down wsl

I guess as a workaround I could add a small script to my bash profile to create the resolv.conf file

@camerondubas
Copy link

I'm experiencing the same behaviour as @m2hd1. My /etc/resolv.conf gets regenerated even though I have set a /etc/wsl.conf.

@jonshipmannwmg
Copy link

Add this to the /etc/wsl.conf file:

[boot]
command = "printf 'nameserver 8.8.8.8\nnameserver 4.4.4.4' > /etc/resolve.conf"

@ten0s
Copy link

ten0s commented Feb 8, 2022

The Boot setting is only available on Windows 11.

https://docs.microsoft.com/en-us/windows/wsl/wsl-config#boot-settings

@ten0s
Copy link

ten0s commented Feb 8, 2022

If your config keeps getting overwritten review
https://docs.microsoft.com/en-us/windows/wsl/wsl-config#the-8-second-rule

@jdgregson
Copy link

Add this to the /etc/wsl.conf file:

    [boot]
    command = "printf 'nameserver 8.8.8.8\nnameserver 4.4.4.4' > /etc/resolve.conf"

This, but /etc/resolv.conf not /etc/resolve.conf (no 'e').

@ghenadiibatalski
Copy link

what the 8.8.8.8 4.4.4.4? does anybody use a corporate dns or a local router? this is not a solution at all

@ten0s
Copy link

ten0s commented Feb 17, 2022

@ghenadiibatalski 8.8.8.8 and 4.4.4.4 are Google DNS servers

Sure, it's not a complete solution, but I don't need access to corporate network inside WSL.
If such access is needed, read https://gist.github.com/coltenkrauter/608cfe02319ce60facd76373249b8ca6?permalink_comment_id=4040950#gistcomment-4040950

@troy-mac
Copy link

troy-mac commented Feb 28, 2022

Thanks man.. Worked like a charm. We use Palo Alto Global Protect for VPN so I left out the final command of
Get-NetAdapter | Where-Object {$_.InterfaceDescription -Match "Cisco AnyConnect"} | Set-NetIPInterface -InterfaceMetric 6000
This was not necessary for me and everything is working now. Thanks Microsoft updates for breaking this...

@Rodeoclash
Copy link

[boot]
command = "printf 'nameserver 8.8.8.8\nnameserver 4.4.4.4' > /etc/resolve.conf"

These are Google provided DNS servers. Just set the values to whatever DNS server you want to use.

@rkhaled0
Copy link

rkhaled0 commented Mar 8, 2022

+1 Thanks for sharing !

@justinholmes
Copy link

justinholmes commented Mar 15, 2022

@ten0s 4.4.4.4 is not Google DNS. Correct ones are 8.8.8.8 8.8.4.4

@j3N0
Copy link

j3N0 commented Mar 22, 2022

The Boot setting works for me.👍

@dungtv994
Copy link

The solution doesn't work for me.
But when I switch to WSL1, DNS is working well.
Does anyone have a solution?

@jonathanmorgan
Copy link

boot setting given by jonshipmannwmg above works for me in Windows 11. Also, works to manually recreate /etc/resolv.conf each time you boot if you don't do the [boot]. Not sure about windows 10.

@epomatti
Copy link

epomatti commented Apr 15, 2022

Based on this gist I created this simple code:

https://github.com/epomatti/wsl2-dns-fix-config

@Dwerg01
Copy link

Dwerg01 commented Jun 4, 2022

Thank you very much.
I love WSL2, but it still has so many annoying issues. Worked for Ubuntu-22.04

@gustavo-lara-molina
Copy link

Based on this gist I created this simple code:

thnks!!!, this works for me, I downloaded the code manually and after run this DNS works in WSL 2 Ubuntu-18.04 Win11

@epomatti
Copy link

@gustavo-lara-molina nice! happy to help

@heatlill
Copy link

heatlill commented Jun 23, 2022

Based on this gist I created this simple code:

https://github.com/epomatti/wsl2-dns-fix-config

My Environment:

  • Corporate environment (remote VPN).
  • Windows 10 host
  • WSL2
  • Ubuntu 22.04 LTS

Steps:

  1. Added the following to /etc/wsl.conf.
[network]
generateResolvConf = false
  1. Backed up then deleted /etc/resolv.conf.
  2. Created a new /etc/resolv.confusing the DNS servers from my VPN connection.
  3. Ran: chattr +i /etc/resolv.conf (Using the last line from run.sh script in the gist above.)

I've restarted WSL several times and my changes are persisting.

@jordanmiracle
Copy link

jordanmiracle commented Jul 1, 2022

This original solution worked perfectly. Before, the only solution seemed to be recreating .ssh keys on every startup, which doesn't make sense, but it had worked twice. Hopefully, this solution will be persistent across reboots. Thank you!

I should say, the main place I noticed the error was trying to push commits. I just finished the last step and went to push and it worked flawlessly.

@marwin1991
Copy link

  1. Find out nameserver with windows powershell (during VPN Session and without) using nslookup
  2. USe sudo touch /etc/wsl.conf and sudo vim /etc/wsl.conf to add:
[network]                                                                        
generateResolvConf = false
  1. Restart wsl (Windows powershell) using wsl --shutdown
  2. Open WSL and remove using rm -f /etc/resolv.conf
  3. Add new file sudo touch /etc/resolv.conf and sudo vim /etc/resolv.conf with:
nameserver X.X.X.X

nameserver Y.Y.Y.Y
  1. Restart wsl (Windows powershell) using wsl --shutdown
  2. Open WSL and remove using wget google.com and test some you corporate domain.

@rimeraz
Copy link

rimeraz commented Jul 26, 2022

  1. Restart wsl (Windows powershell) using wsl --shutdown
  2. Open WSL and remove using wget google.com and test some you corporate domain.

Is there a special reason for the final reboot?

Setting the nameserver works without reboot thus the steps 6 and 7 are usually not required.

@RaketMats
Copy link

Yes, original solution worked for me to. Thanks :)

@ghenadiibatalski
Copy link

DNS resolution is getting fixed after upgrade to Windows 11, before that it won't work well

@Ravaelles
Copy link

Modified script that worked for me.

sudo touch /etc/resolv.conf
chmod 777 /etc/resolv.conf
printf 'nameserver 8.8.8.8\nnameserver 4.4.4.4' > /etc/resolv.conf

@ps2goat
Copy link

ps2goat commented Aug 11, 2022

@ghenadiibatalski I recently did a fresh install of everything on Windows 11 with WSL2 and ubuntu 22, no such luck. It has the same issues as I had on Windows 10.

The [boot] command works well, though I modified it a bit to include the bridge IP that is potentially recreated during WSL restarts. After adding this bit into /etc/wsl.conf, exit wsl and restart it by using wsl --shutdown in a terminal. Re-open your wsl instance afterward, and it will have generated the updated /etc/resolv.conf file with the combined nameservers.

[boot]
    command = "printf \"nameserver 1.1.1.1\n$(cat /etc/resolv.conf)\nnameserver 8.8.8.8\nnameserver 1.0.0.1\n\" > /etc/resolv.conf"

When the resolv.conf is recreated during wsl2 boot, it has the bridge IP in it as the nameserver, and I wanted to retain that for other reasons. Feel free to move $(cat /etc/resolv.conf) around based on your needs. In my case, I only need one main, working DNS toward the top of the list so that things like brew and terraform can work properly.

Others who have several other DNS configs for VPN adapters, etc., may need those auto generated settings as well.

Description of how it works

  1. A subprocess reads the contents of the newly created file at boot, which has the bridge IP in it by default. $(cat /etc/resolv.conf)
  2. The printf command injects the result of that after the first nameserver, and before the other two (configure as needed)
  3. The value to print is surrounded with double quotes, so that variable substitution can happen. These are already in double quotes due to command = "<full command>", so they are escaped: \"
  4. The results of what is printed are written back to /etc/resolv.conf.

Update 2023-08-09

I just realized I had the command writing to resolve.conf, not resolv.conf like I had in bullet point 4, above. I updated the script to use the correct file name resolv.conf.

Due to this comment being buried by newer comments, I've moved it to a separate gist here: https://gist.github.com/ps2goat/f885ad790178ed9e8012b0681a0ef61d

@freelancer1845
Copy link

As this is the first that comes up on google when searching "wsl dns server not working" I'd like to add the solution described here: microsoft/WSL#5256 (comment)
It was the problem for me -> vEthernet blocked by windows defender

@coltenkrauter
Copy link
Author

coltenkrauter commented Aug 30, 2022

Awesome, thanks for sharing.
I am no longer using WSL2 – please let me know if you'd like me to update the gist or add any comments that might help others out.

@plawson
Copy link

plawson commented Aug 31, 2022

[boot]
command = "printf 'nameserver 8.8.8.8\nnameserver 4.4.4.4' > /etc/resolve.conf"

This worked for me on Windows 11

@chujiangke
Copy link

Add this to the /etc/wsl.conf file:

[boot]
command = "printf 'nameserver 8.8.8.8\nnameserver 4.4.4.4' > /etc/resolve.conf"

This worked for me on Windows 11

@giumax87
Copy link

The solution proposed works but I prefere to leave the resolv.conf self generated and add a rule to firewall.
Using powershell:
New-NetFirewallRule -DisplayName "WSL" -Direction Inbound -InterfaceAlias "vEthernet (WSL)" -Action Allow

To get the InterfaceAlias use ipconfig /all

@nikzanda
Copy link

nikzanda commented Oct 9, 2022

Original resolution worked for on Windows 11

@jamezrin
Copy link

The solution proposed works but I prefere to leave the resolv.conf self generated and add a rule to firewall. Using powershell: New-NetFirewallRule -DisplayName "WSL" -Direction Inbound -InterfaceAlias "vEthernet (WSL)" -Action Allow

To get the InterfaceAlias use ipconfig /all

This worked for me

@dpraul
Copy link

dpraul commented Oct 19, 2022

The solution proposed works but I prefere to leave the resolv.conf self generated and add a rule to firewall. Using powershell: New-NetFirewallRule -DisplayName "WSL" -Direction Inbound -InterfaceAlias "vEthernet (WSL)" -Action Allow

To get the InterfaceAlias use ipconfig /all

Another vote for this one! This method is necessary if you have local DNS rules that you want to share with WSL - if you change the nameserver to an external DNS like 8.8.8.8, it will bypass your local DNS entirely. By using the Windows network interface as a nameserver, WSL will share the local DNS with Windows.

@pauloch8
Copy link

The solution proposed works but I prefere to leave the resolv.conf self generated and add a rule to firewall. Using powershell: New-NetFirewallRule -DisplayName "WSL" -Direction Inbound -InterfaceAlias "vEthernet (WSL)" -Action Allow

To get the InterfaceAlias use ipconfig /all

Worked for internet domains, but not for intranet when connected into VPN. Does anyone know why?

@andi-blafasl
Copy link

The solution proposed works but I prefere to leave the resolv.conf self generated and add a rule to firewall. Using powershell: New-NetFirewallRule -DisplayName "WSL" -Direction Inbound -InterfaceAlias "vEthernet (WSL)" -Action Allow

To get the InterfaceAlias use ipconfig /all

Thist work for me for internet and internal corporate names over VPN. But you have to use FQDNs inside WSL2 because the distribution does not know a dns search domain.

@apodworny
Copy link

The "recent solution" worked for me, thanks!

@gavinn212
Copy link

Is there any way to automate that? Now I need to run Get-NetAdapter | Where-Object {$_.InterfaceDescription -Match "Cisco AnyConnect"} | Set-NetIPInterface -InterfaceMetric 6000 every time I connect VPN. Thanks for helping.

@amegbor
Copy link

amegbor commented Nov 4, 2022

Is there any way to automate that? Now I need to run Get-NetAdapter | Where-Object {$_.InterfaceDescription -Match "Cisco AnyConnect"} | Set-NetIPInterface -InterfaceMetric 6000 every time I connect VPN. Thanks for helping.

see this https://gist.github.com/pyther/b7c03579a5ea55fe431561b502ec1ba8

@mikeblakeuk
Copy link

Warning. I cloned the wsl2-dns-fix-config repo in windows so the script had windows line endings. After running the run.sh, i ended up in a right mess
image

@johnorourke
Copy link

Disabling and Re-enabling the WiFi adapter in Windows worked for me - there must be something which refreshes WSL2's networking state after a change of network in Windows. Like other commenters, this only seemed to happen after some mix of VPN connect/disconnect and wifi connect/disconnect.

@janvanveldhuizen
Copy link

This works, as long as I stay home. But my DNS settings are different in the office.
Of course I could use 1.1.1.1 or 8.8.8.8, but then I am going around my Pihole at home.

@BDisp
Copy link

BDisp commented Dec 2, 2022

The first solution work well to me. I would like give my opinion about this. On Ubuntu I did all as the instruction.
On Debian I created the wsl.conf file with only the bellow, as suggested in the resolv.conf comments:

[network]
generateResolvConf = false

In the resolv.conf file I only changed the nameserver and added a secondary nameserver.
After restart Debian I tried do a sudo apt update which run very fast but with error return by the debian site. I tried to open the resolv.conf file but it's not exist anymore. So my tought is despite it not recreating the resolv.conf file, WSL need him to get the dns server. The sudo chattr -f +i /etc/resolv.conf command do the trick by avoiding the resolv.conf file been deleted.
But I didn't done the last command at bellow and it also working well as expected.
Get-NetAdapter | Where-Object {$_.InterfaceDescription -Match "Cisco AnyConnect"} | Set-NetIPInterface -InterfaceMetric 6000
So I would to ask what the above command really do?
By the way, in my machine the InterfaceMetric is 5000 and not 6000.
*Edit
Sorry, I made confusion about this. I see that is only to list the connections where having "Cisco AnyConnect".

Edit:
In pwsh the command to get the ip's address is:
(Get-NetAdapter | Get-DnsClientServerAddress).ServerAddresses

@TR0N-ZEN
Copy link

TR0N-ZEN commented Dec 6, 2022

I fixed it by setting my network in windows to private isntead of public.

@MiguelAnia
Copy link

MiguelAnia commented Dec 7, 2022

Using wsl-vpnkit is a better solution: https://github.com/sakai135/wsl-vpnkit
It resolves the DNS resolution shenanigans, while also allowing connectivity from the WSL distros through VPN, + between Windows host and distros.

@ttigori
Copy link

ttigori commented Jan 12, 2023

The recent solution works perfectly, Thanks !

@izznfkhrlislm
Copy link

Disabling and Re-enabling the WiFi adapter in Windows worked for me - there must be something which refreshes WSL2's networking state after a change of network in Windows. Like other commenters, this only seemed to happen after some mix of VPN connect/disconnect and wifi connect/disconnect.

Surprisingly, this one's worked for me. After some desperate attempt to edit /etc/resolv.conf and adding new firewall rule in PowerShell like what @giumax87 suggests 😅

@yiqiangjizhang
Copy link

sudo touch /etc/resolv.conf
chmod 777 /etc/resolv.conf
printf 'nameserver 8.8.8.8\nnameserver 4.4.4.4' > /etc/resolv.conf

This worked for me

@jangrewe
Copy link

jangrewe commented Feb 3, 2023

That's all you need:

echo -e "[network]\ngenerateResolvConf = false\n" | sudo tee /etc/wsl.conf
echo -e "nameserver 8.8.8.8\n" | sudo tee /etc/resolv.conf

No reboots, no restarts, no line-by-line appending, no messing with non-existent Cisco AnyConnect interfaces. Just those two lines and you're good to go.

Again, this is Linux, not Windows. You don't need to reboot/restart just because you changed your nameserver...

@itsTyrion
Copy link

no change, name resolution still takes like 5 SECONDS. WSL1 AND 2

@kingofwe86
Copy link

After usual windows 11 update:
KB2267602 (1.381.3293.0)

custom resolv.conf solution with Google DNS configured worked for me.
firewall solution (that i preferred in order not to alter the configuration of the wsl) didn't work.

@yiqiangjizhang
Copy link

echo -e "[network]\ngenerateResolvConf = false\n" | sudo tee /etc/wsl.conf
echo -e "nameserver 8.8.8.8\n" | sudo tee /etc/resolv.conf

I used this in the terminal and it worked like a charm! Thanks. I hope I do not have to execute this command every time I use github. Do you know if it is one-time use? or should I run it after executing whenever I reboot my machine?

@BDisp
Copy link

BDisp commented Feb 10, 2023

echo -e "[network]\ngenerateResolvConf = false\n" | sudo tee /etc/wsl.conf
echo -e "nameserver 8.8.8.8\n" | sudo tee /etc/resolv.conf

I used this in the terminal and it worked like a charm! Thanks. I hope I do not have to execute this command every time I use github. Do you know if it is one-time use? or should I run it after executing whenever I reboot my machine?

After the above command is needed to run sudo chattr -f +i /etc/resolv.conf, otherwise the resolv.conf file will be deleted after reboot. See my comment above.

@yiqiangjizhang
Copy link

echo -e "[network]\ngenerateResolvConf = false\n" | sudo tee /etc/wsl.conf
echo -e "nameserver 8.8.8.8\n" | sudo tee /etc/resolv.conf

I used this in the terminal and it worked like a charm! Thanks. I hope I do not have to execute this command every time I use github. Do you know if it is one-time use? or should I run it after executing whenever I reboot my machine?

After the above command is needed to run sudo chattr +i resolv.conf, otherwise the resolv.conf file will be deleted after reboot. See my comment above.

I have the following error when using that command: chattr: No such file or directory while trying to stat resolv.conf then I used this sudo chattr -f +i /etc/resolv.conf and somehow worked. Not sure if it is the correct way

@BDisp
Copy link

BDisp commented Feb 10, 2023

Sorry I didn't write the correct path. Without the -f option it didn't worked?

Edit:
The -f (force) flag is really needed if we want to make all the process at once in the same instance, otherwise this error is raised chattr: Operation not supported while reading flags on /etc/resolv.conf. The -f isn't needed if we exit the distro without executing the chattr command and reopen again, we will find that the /etc/resolv.conf was deleted. Then we must recreate it again with the nameserver and in this case the -f isn't needed. So, my advice is doing all this at once before close the distro by using the -f flag.

@yiqiangjizhang
Copy link

Sorry I didn't write the correct path. Without the -f option it didn't worked?

With the '-f it seem to have worked. Ihave to confirm once I reboot my PC if it still works.

@jangrewe
Copy link

jangrewe commented Feb 10, 2023

Do you know if it is one-time use?

The first line ensures that the resolv.conf does not get generated by WSL - which is kinda obvious from the name of the variable, isn't it? ;-)
The second line is the actual change to Google's DNS servers.
So yes, it's a one-time thing.

@BDisp
Copy link

BDisp commented Feb 10, 2023

Do you know if it is one-time use?

The first line ensures that the resolv.conf does not get generated by WSL - which is kinda obvious from the name of the variable, isn't it? ;-) The second line is the actual change to Google's DNS servers. So yes, it's a one-time thing.

Before only that was not working, despite the obvious, of course, but I admit that perhaps there had been some update in the WSL that now obeys the configuration. So at the time I had to have to use the sudo chattr -f +i /etc/resolv.conf. I never needed to repeat the commands anymore.

@cr0Kz
Copy link

cr0Kz commented Feb 13, 2023

Using WSL 2, after:

  • Adding generateResolvConf = false in /etc/wsl.conf.
  • Shutdown WSL by issuing wsl --shutdown
  • Unlink resolv.conf unlink /etc/resolv.conf

I was able to create /etc/resolv.conf and add nameserver 8.8.8.8.
There was no need for a firewall rule in Windows or the use of chattr +i in my case.

@wh81752
Copy link

wh81752 commented Feb 14, 2023

I got it eventually working. So what is this fuss all about?

It's just that wsl cannot figure out which DNS nameserver to use. Therefore, all that needs to be done is to

  1. manually adjust the DNS nameserver to use (/etc/resolv.conf)
  2. ensure that wsl sticks with your manual adjustment, i.e. prevent /etc/resolv.conf from being overridden

To get a list of nameservers around you do:

rem cmd.exe
ipconfig /all

and search for 'DNS Servers' within the listed network adapters. Blindly using 8.8.8.8 does not make any sense and I really question why someone even gives such an 'hardcoded' advice.

Next, ensure that /etc/wsl.conf contains the line generateResolvConf = false to ensure that handcrafted DNS nameserver is untouched.
By default -- on wsl -- /etc/resolv.conf is linked to a generated file. Therefore you may want to 'unlink' /etc/resolv.conf before changing.

Eventually "restart" wsl to get your changes effective. Usually done like sudo systemctl restart networking and friends. Not working in wsl. Therefore do something like

wsl --terminate <Ubuntu|Debian|whatever>         ;; stop
wsl -d <Ubuntu|Debian|whatever>                        ;; start

Yes, you can also use wsl --shutdown to kill all running distributions. Not polite cause it may also kill your local Docker as collateral damage.

@jangrewe
Copy link

Blindly using 8.8.8.8 does not make any sense and I really question why someone even gives such an 'hardcoded' advice.

Why? Pretty simple: If someone cares enough about which DNS they use, they should have absolutely no issue understanding what that command does, and how it can be changed to any other DNS IP they prefer.
But for all those "ONOES! Y U NO WERKY? HALP! KTHXBYE" type of people, using 8.8.8.8 should be good enough.

So yes, this does make a whole fucking lot of sense, no matter how much you question it.

@BDisp
Copy link

BDisp commented Feb 16, 2023

Using WSL 2, after:

* Adding `generateResolvConf = false` in `/etc/wsl.conf`.

* Shutdown WSL by issuing `wsl --shutdown`

* Unlink resolv.conf `unlink /etc/resolv.conf`

I was able to create /etc/resolv.conf and add nameserver 8.8.8.8. There was no need for a firewall rule in Windows or the use of chattr +i in my case.

I had to repeat all this weird behavior, due a Windows 11 update and I couldn't make any updates again. So with your information about only using unlink /etc/resolv.conf doesn't work att all, because after you close and reopen the distro, the /etc/resolv.conf doesn't exist anymore. Also the command wsl --shutdown doesn't make sense because it will close the distro and when you reopen the /etc/resolv.conf is already deleted. So, only with the sudo chattr -f +i /etc/resolv.conf prevents it from been deleted. Done this to all of my distros and all is working well.
chattr +i is useful for protection from accidental deletion by root. Also an immutable file cannot be renamed or moved from one directory to another.
For the chattr -f see this my comment https://gist.github.com/coltenkrauter/608cfe02319ce60facd76373249b8ca6?permalink_comment_id=4466805#gistcomment-4466805

@cr0Kz
Copy link

cr0Kz commented Feb 17, 2023

Using WSL 2, after:

* Adding `generateResolvConf = false` in `/etc/wsl.conf`.

* Shutdown WSL by issuing `wsl --shutdown`

* Unlink resolv.conf `unlink /etc/resolv.conf`

I was able to create /etc/resolv.conf and add nameserver 8.8.8.8. There was no need for a firewall rule in Windows or the use of chattr +i in my case.

I had to repeat all this weird behavior, due a Windows 11 update and I couldn't make any updates again. So with your information about only using unlink /etc/resolv.conf doesn't work att all, because after you close and reopen the distro, the /etc/resolv.conf doesn't exist anymore. Also the command wsl --shutdown doesn't make sense because it will close the distro and when you reopen the /etc/resolv.conf is already deleted. So, only with the sudo chattr -f +i /etc/resolv.conf prevents it from been deleted. Done this to all of my distros and all is working well. chattr +i is useful for protection from accidental deletion by root. Also an immutable file cannot be renamed or moved from one directory to another. For the chattr -f see this my comment https://gist.github.com/coltenkrauter/608cfe02319ce60facd76373249b8ca6?permalink_comment_id=4466805#gistcomment-4466805

I should've mentioned I am running Windows 10. My bad!

@Livb-VRC
Copy link

resolv.conf worked for me but after 10s DNS stops working again. I'm so confused

@BDisp
Copy link

BDisp commented Feb 19, 2023

resolv.conf worked for me but after 10s DNS stops working again. I'm so confused

Please describe all the steps you did.

@amalmadhu06
Copy link

Thankyou
More recent resolution worked for me.

@saber3188
Copy link

thank you,More recent resolution worked for me.

@Abuelela2022
Copy link

You are the best after 2 hours searching for a solution. you solve it in simple way thank you

@KonanTheLibrarian
Copy link

KonanTheLibrarian commented Jul 26, 2023

DNS on WSL2 STILL JUST BREAKS: CLOSING THOUSANDS OF BUG REPORTS ON THIS 10 YEAR OLD BUG (WHICH IS NOT FIXED) IS WEIRD!

I have implemented that hard coded DNS solution (above) and it is a lot better, but WSL2 still looses it's DNS even if you disconnect briefly and reconnect your IPsec VPN. Once that happens still have to reboot. (I am running WSL2 on top end Dell laptop with up-to-date bios and Windows 10.)

When running ordinary applications under Windows or on a Linux PC, any disconnection of the network and reconnection allows all applications to reconnect to the network no problem; not so with WSL! When running WSL, DNS resolution is lost even with a brief disconnection or the lease time on the network driver laps and reconnects, after that you can’t connect or even ping devices unless you reboot!

Even with millions of complaints, and thousands of bug reports, this bug has been persistent for almost a decade and NOT FEXED IN JULY 2023! This is so serious many developers avoid all Docker development under WSL and Windows. When Windows programmers write Linux network code, what could possibly go wrong?

WSL team members even close bug reports rather than combine the data from thousands of similar reports. When reports are closed so that others can’t comment the geniuses have magically fixed the major bug right? NOT! The use of Docker Desktop makes it 100 times worse, but fortunately Docker Desktop is NOT Docker and many people run WSL2 without Docker Desktop.

@rrlevy
Copy link

rrlevy commented Aug 7, 2023

Damn, I was following this instruction but somehow I broke my wsl.
My ~ folder has changed and I can't find my files. It seems it is now logging in as a root user, i don't think it was doing that before

@rrlevy
Copy link

rrlevy commented Aug 7, 2023

Damn, I was following this instruction but somehow I broke my wsl. My ~ folder has changed and I can't find my files. It seems it is now logging in as a root user, i don't think it was doing that before

I fixed it!

Just enter: ubuntu config --default-user YOUR_USERNAME

The user was still there! It was just logging in always as root now for some reason.

@ThePlenkov
Copy link

ThePlenkov commented Aug 7, 2023

Here is my solution for this problem. Basically I have accumulated everything mentioned above:
https://gist.github.com/ThePlenkov/6ecf2a43e2b3898e8cd4986d277b5ecf

  • script removes all nameservers in /etc/resolv.conf and replaces them with actual IPs from powershell
sudo sed -i '/nameserver/d' /etc/resolv.conf
powershell.exe -Command '(Get-DnsClientServerAddress -AddressFamily IPv4).ServerAddresses | ForEach-Object { "nameserver $_" }' | tr -d '\r' | sudo tee -a /etc/resolv.conf > /dev/null
  • script is configured as a boot command which is available in Win 11. If it's applicable for you - it helps a lot

@q-yonlugoh
Copy link

@ThePlenkov That worked for me, thanks!

@will397
Copy link

will397 commented Aug 23, 2023

@ThePlenkov Superb. Great instruction, efficient solution!

@droidecahedron
Copy link

@ThePlenkov

Excellent, thanks so much.

@naml3i
Copy link

naml3i commented Sep 6, 2023

That's all you need:

echo -e "[network]\ngenerateResolvConf = false\n" | sudo tee /etc/wsl.conf
echo -e "nameserver 8.8.8.8\n" | sudo tee /etc/resolv.conf

No reboots, no restarts, no line-by-line appending, no messing with non-existent Cisco AnyConnect interfaces. Just those two lines and you're good to go.

Again, this is Linux, not Windows. You don't need to reboot/restart just because you changed your nameserver...

Thanks, this answer is really clean and on point.

@BillBrinkley58
Copy link

Thanks for the help. This worked for me.

@KonanTheLibrarian
Copy link

BILLION DOLLAR MICROSOFT WSL BUG FIXED AFTER 13 YEARS = WSL DNS Network Failure with VPNs resulted in A TOTAL REWRITE OF WSL2 by October 2023 - PING FAILED IN WSL

Expect this WSL2 broken DNS related issues (above) to be fixed from October 2023.
N.B. Now you have to change all your WSL Linux Network configs to match the totally new design.
Eventually fixed mentioned here

Why be so angry? When I said it cost MICROSOFT BILLIONS over 13 years you laughed at me. I was right - TOTALLY VINDICATED - THIS BUG STUNG THEIR BIGGEST CUSTOMERS THE MOST SO THAT WSL WAS REJECTED! The extent to which WSL was rejected by ALL the biggest companies is staggering! Hell they all used VPNs and Docker! Thousands of the SAME bug reports GOT CLOSED BY GENIUSES that can't fix the bug or bother to reproduce it and FALSELY CLAIM "UNABLE TO REPRODUCE". The bug was there for 13 years breaking WSL1 and Microsoft biggest customers who use compulsory VPNs which broke WSL2 networking DNS and a primary symptom was Ping failures.

  • This bug occurred RANDOMLY because WSL2 Network/Subnet settings WERE DELIBERATLY RANDOM - RIGHT IN THE DESIGN! NO JOKE!
  • Most bugs are fixed by minor upgrades but this bug was fully rooted in the design, they had to rip WSL NETWORK GARBAGE CODE out and start over!
  • The bug was TOTALLY IGNORED BY GENEUSES FOR OVER A DECADE! GENIUSES KEPT ON AND ON CLOSING BUG REPORTS!
  • I started to realise that this bug revealed MONSTER SECURITY HOLES IN WSL NETOWRKS making it totally insecure. NOW THEY DID NOT IGNORE ME, STOPPED RIDICULING ME!
  • So in 2023 they rewrote the hole of WSL2 Network configuration which was more than a mess: it was a pile ...

ORIGINAL SYMPTOMS of WSL2 Networks Breaking with VPNs RANDOMLY WORKING

ROOT CAUSE - BECAUSE WSL1 & WSL2 RANDOMLY SELECT SUBNETS, SO THE CORPORATIONS VPN (firewall) REJECTS SOME OF THEM - RANOMLY - NOT THE CORPORATIONS FAULT!

DNS on WSL2 WITH VPNs JUST BREAKS: CLOSING THOUSANDS OF BUG REPORTS ON THIS 10 YEAR OLD BUG (WHICH IS NOT FIXED FOR SUCH A LONG TIME) IS WEIRD!

Some 20 solutions claim to work but the root cause of why the bug keeps getting closed and then reopened is that WSL2 network WORKS RANDOMLY - THIS IS BY DESIGN BECAUSE WSL2 RANDOMLY SELECTS A SUBNET!!!!!!!!!!!!!!!! thus WSL2 still looses it's DNS even if you disconnect briefly and reconnect your IPsec VPN ( RANDOM SUBNET IS CHOSEN ). Once the wrong random subnet is REJECTED by the corporations VPN you still have to reboot. (I am running WSL2 on top end Dell laptop with up-to-date bios and Windows 10.)

When running ordinary applications under Windows or on a Linux PC, any disconnection of the network and reconnection allows all applications to reconnect to the network no problem; not so with WSL! When running WSL, DNS resolution is lost even with a brief disconnection or the lease time on the network driver laps and reconnects, after that you can’t connect or even ping devices unless you reboot!

Even with millions of complaints, and thousands of bug reports, this bug has been persistent for almost a decade and NOT FEXED IN JULY 2023! This is so serious many developers avoid all Docker development under WSL and Windows. When Windows programmers write Linux network code, what could possibly go wrong?

WSL team members even close bug reports rather than combine the data from thousands of similar reports. When reports are closed so that others can’t comment the geniuses have magically fixed the major bug right? NOT! The use of Docker Desktop makes it 100 times worse, but fortunately Docker Desktop is NOT Docker and many people run WSL2 without Docker Desktop.

@ThePlenkov
Copy link

ThePlenkov commented Oct 16, 2023

@KonanTheLibrarian this solution works in WSL2 with vpn very smoothly (especially on win11). https://gist.github.com/ThePlenkov/6ecf2a43e2b3898e8cd4986d277b5ecf

But in general I share your frustration. I'd also prefer if generateResolvConf is fixed by taking the right DNS, also including VPN connections.

@heaviss
Copy link

heaviss commented Oct 18, 2023

You might also want to add dns key into docker json config (worked for me)
изображение

@iiicebearrr
Copy link

It works!!!
Just follow the 1~13 steps

@gto406
Copy link

gto406 commented Dec 20, 2023

The provided steps worked great, thank-you! I utilized Google’s DNS (8.8.8.8/8.8.4.4) and the fix worked like a charm. 🤘

@andradei
Copy link

andradei commented Jan 5, 2024

The "More recent resolution" worked.
Didn't run step 13 though.

For the benefits WSL provide, what a mess this issue is... Thank for the solution.

@teeesss
Copy link

teeesss commented Jan 5, 2024

I like this approach.

Makes /root/resolv.conf.sh executable using wsl.conf boot command
Deletes the /etc/resolv.conf file on start-up
Runs the script /etc/resolv.conf.sh and populated with DNS servers from the script.
Change the servers as desired: DNS_SERVERS=("9.9.9.9" "1.1.1.1" "8.8.8.8")
Outputs a log file to /root/resolv.conf.log

vi /etc/wsl.conf

[boot]
command = /bin/bash chmod +x /root/resolv.conf.sh; /bin/bash /root/resolv.conf.sh > /root/resolv.conf.log 2>&1
systemd=true

[network]
generateResolvConf = false

vi /root/resolv.conf.sh

#!/bin/bash

# Specify the DNS servers
DNS_SERVERS=("9.9.9.9" "1.1.1.1" "8.8.8.8")

# Log file path
LOG_FILE="/root/resolv.conf.log"

# Delete the existing /etc/resolv.conf
sudo rm /etc/resolv.conf

# Create or update the /etc/resolv.conf file
for server in "${DNS_SERVERS[@]}"; do
    echo "nameserver $server" | sudo tee -a /etc/resolv.conf
done

# Log the changes to the specified log file
echo "DNS servers updated: $(date)" | sudo tee -a "$LOG_FILE"

@samuel-andres
Copy link

I like this approach.

Makes /root/resolv.conf.sh executable using wsl.conf boot command Deletes the /etc/resolv.conf file on start-up Runs the script /etc/resolv.conf.sh and populated with DNS servers from the script. Change the servers as desired: DNS_SERVERS=("9.9.9.9" "1.1.1.1" "8.8.8.8") Outputs a log file to /root/resolv.conf.log

vi /etc/wsl.conf

[boot]
command = /bin/bash chmod +x /root/resolv.conf.sh; /bin/bash /root/resolv.conf.sh > /root/resolv.conf.log 2>&1
systemd=true

vi /boot/resolv.conf.sh

#!/bin/bash

# Specify the DNS servers
DNS_SERVERS=("9.9.9.9" "1.1.1.1" "8.8.8.8")

# Log file path
LOG_FILE="/root/resolv.conf.log"

# Delete the existing /etc/resolv.conf
sudo rm /etc/resolv.conf

# Create or update the /etc/resolv.conf file
for server in "${DNS_SERVERS[@]}"; do
    echo "nameserver $server" | sudo tee -a /etc/resolv.conf
done

# Log the changes to the specified log file
echo "DNS servers updated: $(date)" | sudo tee -a "$LOG_FILE"

Works great! Just a typo in the path of the script /boot/resolv.conf.sh should be /root/resolv.conf.sh, right?

@teeesss
Copy link

teeesss commented Jan 6, 2024 via email

@bayeslearner
Copy link

What is this solution to? I am switching back to windows+WSL after abandoning it (due to various networking nags), and I remember from a few years ago that I had to toggle this resolv.conf between public DNS servers and corporate DNS server when the windows host is off VPN.

@samuel-andres
Copy link

@bayeslearner
The solution from @teeesss fixes the issue of failing DNS because of conflicts with the IP directions randomly assigned and instead using public DNS. Just make sure to have this in /etc/wsl.conf:

[network]
generateResolvConf = false

@flogr
Copy link

flogr commented Jan 16, 2024

Here is my solution for this problem. Basically I have accumulated everything mentioned above: https://gist.github.com/ThePlenkov/6ecf2a43e2b3898e8cd4986d277b5ecf

  • script removes all nameservers in /etc/resolv.conf and replaces them with actual IPs from powershell
sudo sed -i '/nameserver/d' /etc/resolv.conf
powershell.exe -Command '(Get-DnsClientServerAddress -AddressFamily IPv4).ServerAddresses | ForEach-Object { "nameserver $_" }' | tr -d '\r' | sudo tee -a /etc/resolv.conf > /dev/null
  • script is configured as a boot command which is available in Win 11. If it's applicable for you - it helps a lot

This works for me! Thank you so much!

@404whoami
Copy link

Here is my solution for this problem. Basically I have accumulated everything mentioned above: https://gist.github.com/ThePlenkov/6ecf2a43e2b3898e8cd4986d277b5ecf

  • script removes all nameservers in /etc/resolv.conf and replaces them with actual IPs from powershell
sudo sed -i '/nameserver/d' /etc/resolv.conf
powershell.exe -Command '(Get-DnsClientServerAddress -AddressFamily IPv4).ServerAddresses | ForEach-Object { "nameserver $_" }' | tr -d '\r' | sudo tee -a /etc/resolv.conf > /dev/null
  • script is configured as a boot command which is available in Win 11. If it's applicable for you - it helps a lot

thanks it worked for me

@volehuy1998
Copy link

Didn't work like a charm. Thank so much

@gtedavid
Copy link

gtedavid commented Apr 9, 2024

So here is my configuration
Version WSL : 2.1.5.0
Version du noyau : 5.15.146.1-2
Version WSLg : 1.0.60
Windows 11 version : 23h2 22631.3296

I don't know how it happened, but from the day to the next it stopped working.
I did the original resolution, but putting my router's ip worked.

Original resoltuion:

1. Create a file: /etc/wsl.conf.
2. Put the following lines in the file in order to ensure the your DNS changes do not get blown away

[network]
generateResolvConf = false

3. In a cmd window, run wsl --shutdown
4. Restart WSL2
5. Create a file: /etc/resolv.conf. If it exists, replace existing one with this new file.
6. Put the following line in the file

nameserver 8.8.8.8 # Or use your DNS server instead of 8.8.8.8 which is a Google DNS server

7. Repeat step 3 and 4. You will see git working fine now.

I noticed that the IP that's in the /etc/resolv.conf is the one indicated here (ipconfig /all)
image
Which is apparently the WSL Hyper-V firewall....
would it mean that the issue lies in the "forwarding" or letting through of that Hyper V firewall and the host ? at least for dns, the traceroute seemed to work fine

@s1rens
Copy link

s1rens commented May 5, 2024

Maybe this will help someone (source)

Set-NetFirewallHyperVVMSetting -Name '{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}' -DefaultOutboundAction Allow

As @gtedavid mentioned it seems like Hyper-V is blocking some outbound connection by default, for whatever reason.
My setup is with Mullvad VPN. I am also using Windows Firewall Control tool by Malwarebytes.

To add my Mullvad VPN DNS server to WSL, do ipconfig.exe /all and grab the DNS address under your VPN name. Then sudo nano /etc/resolv.conf and add:
nameserver <IPHERE>
I did have to set Local network sharing ON, on Mullvad VPN settings. Try that if you still have issues and you're using a VPN.

@ThePlenkov
Copy link

ThePlenkov commented May 14, 2024

Dear all, happy to say that mentioned above problem is not a problem anymore since version 22H2 with DNS tunneling introduced .

The only step step you need to perform:

[wsl2]
dnsTunneling=true

That's it. We waited for this solution for years. It's enabled by default since WSL 2.2.1

@ur3an0
Copy link

ur3an0 commented May 17, 2024

BILLION DOLLAR MICROSOFT WSL BUG FIXED AFTER 13 YEARS = WSL DNS Network Failure with VPNs resulted in A TOTAL REWRITE OF WSL2 by October 2023 - PING FAILED IN WSL

Expect this WSL2 broken DNS related issues (above) to be fixed from October 2023. N.B. Now you have to change all your WSL Linux Network configs to match the totally new design. Eventually fixed mentioned here

Why be so angry? When I said it cost MICROSOFT BILLIONS over 13 years you laughed at me. I was right - TOTALLY VINDICATED - THIS BUG STUNG THEIR BIGGEST CUSTOMERS THE MOST SO THAT WSL WAS REJECTED! The extent to which WSL was rejected by ALL the biggest companies is staggering! Hell they all used VPNs and Docker! Thousands of the SAME bug reports GOT CLOSED BY GENIUSES that can't fix the bug or bother to reproduce it and FALSELY CLAIM "UNABLE TO REPRODUCE". The bug was there for 13 years breaking WSL1 and Microsoft biggest customers who use compulsory VPNs which broke WSL2 networking DNS and a primary symptom was Ping failures.

  • This bug occurred RANDOMLY because WSL2 Network/Subnet settings WERE DELIBERATLY RANDOM - RIGHT IN THE DESIGN! NO JOKE!
  • Most bugs are fixed by minor upgrades but this bug was fully rooted in the design, they had to rip WSL NETWORK GARBAGE CODE out and start over!
  • The bug was TOTALLY IGNORED BY GENEUSES FOR OVER A DECADE! GENIUSES KEPT ON AND ON CLOSING BUG REPORTS!
  • I started to realise that this bug revealed MONSTER SECURITY HOLES IN WSL NETOWRKS making it totally insecure. NOW THEY DID NOT IGNORE ME, STOPPED RIDICULING ME!
  • So in 2023 they rewrote the hole of WSL2 Network configuration which was more than a mess: it was a pile ...

ORIGINAL SYMPTOMS of WSL2 Networks Breaking with VPNs RANDOMLY WORKING

ROOT CAUSE - BECAUSE WSL1 & WSL2 RANDOMLY SELECT SUBNETS, SO THE CORPORATIONS VPN (firewall) REJECTS SOME OF THEM - RANOMLY - NOT THE CORPORATIONS FAULT!

DNS on WSL2 WITH VPNs JUST BREAKS: CLOSING THOUSANDS OF BUG REPORTS ON THIS 10 YEAR OLD BUG (WHICH IS NOT FIXED FOR SUCH A LONG TIME) IS WEIRD!

Some 20 solutions claim to work but the root cause of why the bug keeps getting closed and then reopened is that WSL2 network WORKS RANDOMLY - THIS IS BY DESIGN BECAUSE WSL2 RANDOMLY SELECTS A SUBNET!!!!!!!!!!!!!!!! thus WSL2 still looses it's DNS even if you disconnect briefly and reconnect your IPsec VPN ( RANDOM SUBNET IS CHOSEN ). Once the wrong random subnet is REJECTED by the corporations VPN you still have to reboot. (I am running WSL2 on top end Dell laptop with up-to-date bios and Windows 10.)

When running ordinary applications under Windows or on a Linux PC, any disconnection of the network and reconnection allows all applications to reconnect to the network no problem; not so with WSL! When running WSL, DNS resolution is lost even with a brief disconnection or the lease time on the network driver laps and reconnects, after that you can’t connect or even ping devices unless you reboot!

Even with millions of complaints, and thousands of bug reports, this bug has been persistent for almost a decade and NOT FEXED IN JULY 2023! This is so serious many developers avoid all Docker development under WSL and Windows. When Windows programmers write Linux network code, what could possibly go wrong?

WSL team members even close bug reports rather than combine the data from thousands of similar reports. When reports are closed so that others can’t comment the geniuses have magically fixed the major bug right? NOT! The use of Docker Desktop makes it 100 times worse, but fortunately Docker Desktop is NOT Docker and many people run WSL2 without Docker Desktop.

thats is working for mee! thanks!!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment