Change DNS Server on Linux

Ubuntu

Editing the DNS servers on Ubuntu is an easy task, here is a little documentation to how to do it.

Check your current configuration

To view the current DNS servers that are being used per interface, you can use this command :

resolvectl status

Or this one for Ubuntu 20.04 or newer :

systemd-resolve --status

These commands will show you the DNS server(s) being used by each network interface.

Edit DNS servers temporarily

To temporarily edit the DNS server, edit the /etc/resolv.conf file.

In /etc/resolv.conf, the line which starts with the keyword nameserver deals with DNS Servers.

Do not remove the line that says nameserver 127.0.0.53. Comment it out by putting a pound/hash symbol at the beginning of that line.

Add a line for every DNS server you’d like to add, here an example with Cloudflare DNS servers :

nameserver 1.1.1.2
nameserver 1.0.0.2

Here we add two DNS servers one main and one as a fallback;

You can then verify if the DNS server changed with the help of dig command.

$ dig google.com | grep SERVER
;; SERVER: 1.1.1.2#53(1.1.1.2) (UDP)

Grep-ing the output, we see that Cloudflare’s DNS servers are being used. That confirms that the temporary change in DNS server was in effect immediately.

Permanently change DNS

If you want to permanently change your DNS server (Persists after a reboot) you will have to edit the YAML network config file that resides in the /etc/netplan/ directory.

Before that, note down the name of your network interface beforehand. You can do so using the ip command:

ip add

Usually, there is only one file in /etc/netplan/ directory, but the name is mostly different. If there are multiple files, grep all files for your interface name. That should narrow down the candidate file to one.

grep -H INTERFACE_NAME *.*

Once you know the filename, open it for editing. You should see something similar to this output :

network:
  ethernets:
    enp1s0:
      dhcp4: true
  version: 2

My network interface is called ‘enp1s0‘, yours might be different.

Under my interface, I will add the nameservers field (below, not under dhcp), and another filed called addresses under it as well. I will specify the address in a bracket, separated by commas, like so :

network:
  ethernets:
    enp1s0:
      dhcp4: true
      nameservers:
        addresses: [1.1.1.2, 1.0.0.2]
  version: 2

Once the file is edited, save modifications and exit.

Then, run the following command to make changes effective:

sudo netplan apply

Your DNS servers are now edited.