WSL2 apt update not working

I have recently set up Windows Subsystem for Linux (WSL2) on my Windows 10 laptop and installed Ubuntu 20.04 LTS. When i tried ‘apt update’ on Ubuntu distro, it failed with following error messages.

> sudo apt-get update
Err:1 http://security.ubuntu.com/ubuntu bionic-security InRelease
  Temporary failure resolving 'security.ubuntu.com'
Err:2 http://archive.ubuntu.com/ubuntu bionic InRelease
  Temporary failure resolving 'archive.ubuntu.com'
Err:3 http://archive.ubuntu.com/ubuntu bionic-updates InRelease
  Temporary failure resolving 'archive.ubuntu.com'
Err:4 http://archive.ubuntu.com/ubuntu bionic-backports InRelease
  Temporary failure resolving 'archive.ubuntu.com'

I did the following to get it working.

Step #1.

On the Ubuntu distro, create a file at this location /etc/wsl.conf.

The file should have the following configuration.

[network]
generateResolvConf = false

If we don’t set this file, WSL will automatically load a default /etc/resolv.conf with default namesever configuration.

Shut down and restart the distro.

Step #2

Delete the default /etc/resolv.conf file.

sudo rm /etc/resolv.conf

Create a new /etc/resolv.conf with the following entry.

nameserver 8.8.8.8

Now, restart the WSL2 and open the distro again. The apt update on WSL2 should work like a charm.