Skip to content

Linux Foundations / Follow traffic and find the fault ยท Step 32 of 46

Lesson: /etc/hostsSwitch
โ† Linux Foundations

Network operations

/etc/hosts

Use the /etc/hosts file to map names to addresses on a single Linux machine.

Before DNS existed, computers kept a list of names in a text file. Linux still has it: /etc/hosts. It is handy for testing and for small private networks.

The format

Each line holds an IP address, then one name, then optional aliases, separated by spaces or tabs. Anything after # is a comment.

$ cat /etc/hosts
127.0.0.1    localhost
127.0.1.1    mylaptop
::1          localhost ip6-localhost ip6-loopback
192.168.1.20 nas.home.arpa nas   # file server

The 127.0.1.1 line is a Debian and Ubuntu habit. Other distributions may not have it.

Editing it

The file belongs to root, so use sudo:

$ sudoedit /etc/hosts

Add a line such as:

192.0.2.50   shop.test

New lookups normally see the change immediately, with no service restart. A running program, such as a browser, may keep its own cache for a while.

Lookup order

On most systems /etc/nsswitch.conf contains something like hosts: files dns. Because files comes first, an entry here wins over DNS on that machine. Other computers are not affected.

This lets you preview a website on a new server before changing its public DNS record.

Testing an entry

getent uses the same system lookup as most programs:

$ getent hosts shop.test
192.0.2.50      shop.test

dig and nslookup send questions straight to a DNS server, so they do not follow nsswitch.conf and are the wrong tools for this test. Note that a local resolver such as systemd-resolved can read /etc/hosts itself, so you may see the entry through it.

Limits

  • No wildcards: *.shop.test does not work. List each name.
  • No port numbers: the file maps names to addresses only.
  • It does not scale: every machine needs its own copy.

Pointing a name at 127.0.0.1 sends programs that use the system lookup to your own machine, a simple way to block a site. Remember old entries too. A forgotten line is a classic reason why one machine reaches the wrong server while everyone else is fine.

Practise editing and viewing files in the files and links lab.

Try it

  1. Run cat /etc/hosts and identify each address and name.
  2. On a test machine, add 127.0.0.1 myapp.test, then run getent hosts myapp.test.
  3. Run ping -c 1 myapp.test, then remove the line again.

Check your understanding

/etc/hosts

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.