How to Edit the Hosts File in Ubuntu Linux

The hosts file which is located at /etc/hosts is a very important network configuration file. The /etc/hosts file is a static DNS file with a list of computer names and their corresponding addresses.

The default hosts file of Ubuntu 18.04 Server
The default hosts file of Ubuntu 18.04 Server

Adding Hosts to /etc/hosts

To edit or add a new host to the hosts file, you need to open this file in a text editor. You can use any editor that you like, but if you are working on an Ubuntu server, you need to use a command line editor like vim, nano or emacs.

vim /etc/hosts

The format of the /etc/hosts file is very simple. Each DNS entry should contain at least two columns. The first column has the IP address of the computer, and the second column specifies the domain name/hostname.

192.168.1.10    server1.example.com

This tells the Ubuntu system that IP address of the server1.example.com is 192.168.1.10 (simple as that).

The domain name or the hostname can be provided as a short name (e.g. server1), or as a Fully qualified domain name (FQDN) like www.example.com.

192.168.1.10 server1
192.168.1.20 server2
192.168.1.30 www.example.com

If a computer has more than one name, you can specify more than one name on a single line as shown in the following screenshot.

ubuntu hosts file

In the example, the 192.168.1.10 host has both the short name (server1) and fully qualified domain name (server1.localdomain.local) included in the Ubuntu hosts file.

Ubuntu utilizes the /etc/hosts file, as well as DNS services to look up IP Addresses. When communicating with a remote computer by their name (instead of IP address), the Ubuntu domain name lookup service looks first in the /etc/hosts file before consulting DNS servers.

If an entry found in this file, the Ubuntu system will not communicate with a DNS server to resolve the IP address. Therefore, you can use the /etc/hosts file is to override an address that a DNS server is giving you.

However, this also means if the name record found in this file is incorrect, then the communication will fail. When you troubleshoot such problem make sure to check the /etc/hosts file to see if there are any DNS record for the given domain name.