The Hosts file allows us to resolve DNS queries locally, which can be very useful for new projects if DNS changes have not yet propagated for a domain we own or if we do not yet have a domain and need to run tests with DNS queries.
Changes we make to the hosts file will only affect the local server we are configuring and will have no effect on other servers. Below, we explain how to enable editing of the hosts file so that changes persist when we restart the server.
Procedure for disabling overwriting of the hosts file
Notice
If you recently created the server on Clouding, you do not need to make any configuration changes.
The first step is to prevent the Cloud Init service from managing the hosts file, because if we try to edit the hosts file directly and restart the server, we will find that the hosts file has been overwritten with the initial values.
To prevent Cloud init from controlling the hosts file, we must perform the following steps:
Ubuntu 18.04
Edit the following Cloud-Init configuration file:
# vi /etc/cloud/cloud.cfgFind the "manage_etc_hosts" variable and set it to false.
manage_etc_hosts: false Ubuntu 16.04, Debian 9 and Centos 7
Edit the following Cloud-Init configuration file:
# vi /etc/cloud/cloud.cfgAdd the following variable below "disable_root: false":
manage_etc_hosts: false In the section "cloud_init_modules", we must remove the following module:
- update_etc_hosts
Centos 8 and Debian 10
Edit the following Cloud-Init configuration file:
# vi /etc/cloud/cloud.cfg.d/99_clouding.cfg Add the following variable below "disable_root: false":
manage_etc_hosts: false In the section "cloud_init_modules", we must remove the following module:
- update_etc_hosts With these changes, we can now edit the hosts file, and the changes will persist when we restart the server.
Example of an entry in the Hosts file
If we wanted our server to perform the DNS query for "mail.example.com" locally, we would need to perform the following steps:
Edit the hosts file:
# vi /etc/hostsAdd the following line:
127.0.0.1 mail.example.com Before making the change, if we ping mail.example.com, the result would be as follows:
root@mail:~# ping mail.example.com
ping: mail.example.com: Name or service not known However, after adding "127.0.0.1 mail.example.com", we can see that the DNS query now returns a response with the server's own "loopback" IP:
root@mail:~# ping mail.example.com
PING mail.example.com (127.0.0.1) 56(84) bytes of data.
64 bytes from mail.example.com (127.0.0.1): icmp_seq=1 ttl=64 time=0.039 ms
64 bytes from mail.example.com (127.0.0.1): icmp_seq=2 ttl=64 time=0.040 ms If the DNS query we want to make refers to an external server, simply replace the IP 127.0.0.1 with the external server's public IP.
With these simple steps, we can add entries to "/etc/hosts" so that the server resolves DNS queries locally.