You might want to have your own /etc/resolv.conf but it keeps getting overwritten or lost. I have the solution!

On systems like Ubuntu 18.04, by default the file /etc/resolv.conf is controlled by systemd-resolved. Usually it fetches the DNS servers and domain name (search domain) from DHCP and writes it to /etc/resolv.conf which the system then reads to know where to send DNS requests. More accurately, it sets itself as DNS server and forwards the requests to the actual DNS servers.

Getting rid of systemd-resolved

So the first step to have your own resolv.conf without it being overwritten, is to disable systemd-resolved which can be done easily with:

sudo systemctl disable systemd-resolved
sudo systemctl stop systemd-resolved

But you might notice that if you modify your file now, while the changes persist, after a reboot the file will be completely gone.

So, the next step is to delete the original file, recreate it with your custom settings and then protect it from being overwritten or deleted.

sudo rm /etc/resolv.conf
sudo nano /etc/resolv.conf
sudo chattr +i /etc/resolv.conf

The first command deletes the original file, the second opens the editor nano (you can also use vi or vim or whatever you like) so you can enter your options and the last command changes the attributes (chattr), adding “immutable” (+i) to it which means nothing and no one can overwrite or delete this file until that attribute is removed.

⚠️ You must delete the original file first, otherwise chattr might give you an error message.

An example resolv.conf could be as simple as:


Which in this case would be setting the system to resolve domain names with Cloudflare’s public resolvers.

Making changes or going back to systemd-resolved

To undo those changes or modify /etc/resolv.conf you need to remove the immutable flag with:

sudo chattr -i /etc/resolv.conf

You can then modify the file and then add the immutable flag again.

To go back to using systemd-resolved, after undoing the changes and removing the immutable flag, simply run:

systemctl enable systemd-resolved
systemctl start systemd-resolved

And that’s all there is to it!