How to make NetworkManager add a DNS server at the top of /etc/resolv.conf?

I accidentally created a duplicate question here. The answer is there, but essentially, you need to create:

/etc/dhcp/dhclient.conf

if it doesn't already exist, and add:

prepend domain-name-servers [ip address of server];

Don't forget the semicolon at the end!

After that, simply rebooting automagically moved the 'nameserver [ip address of server]' line in the '/etc/resolv.conf' up to the top!


I don't see which system to address specifically, but if yours is using resolvconf, try the following as root (su - or sudo -i):

echo 'nameserver 10.165.74.2' >> /etc/resolvconf/resolv.conf.d/head
resolvconf -u

There is a warning in that file which states that manual changes will be overwritten; but, in context, the message applies to /etc/resolv.conf, not /etc/resolvconf/resolv.conf.d/head.

This should place the desired name server first in the list. Of course, if this works on your operating system, then 10.165.74.2 can be removed from NetworkManager.

The local resolver, dnsmasq, is also an excellent path forward. Using dnsmasq, one can utilize much more control over DNS and DHCP. For example, in this scenario, dnsmasq can query a specific name server based on a specified domain name with its server option. See a snippet from dnsmasq.conf that might pertain to your objective below.

# Add other name servers here, with domain specs if they are for
# non-public domains.
server=/our-company-domain.com/10.165.74.2

Update

Thanks for mentioning the operating system. On CentOS 7, there are many methods. In the GUI, click Applications > System Tools > Settings > Network. Select a connection to configure.

CentOS 7 NetworkManager - Configure Connection

Turn off Automatic DNS and supply name servers. Apply the configuration.

CentOS 7 NetworkManager - Apply Static DNS Settings

Next time NetworkManager starts that connection, it writes the custom values. (While testing, I turned the network off and then on again because I had two network connections.)

According to documentation,

  1. A simple curses-based text user interface (TUI) for NetworkManager, nmtui, is available.
  2. A command-line tool, nmcli, is provided to allow users and scripts to interact with NetworkManager. Note that nmcli can be used on GUI-less systems like servers to control all aspects of NetworkManager. It is on an equal footing with the GUI tools.

In particular, the nmcli documentation looked very good.