Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk8 min

How to Configure the /etc/hosts File on Ubuntu

A practical Ubuntu guide to backing up, editing, testing, and troubleshooting /etc/hosts entries, including localhost conventions, aliases, hostname changes, and systemd-resolved behavior.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Ubuntu’s /etc/hosts file is a local table that maps IP addresses to hostnames. To configure it safely, back it up, edit it with root privileges, preserve Ubuntu’s localhost entries, add each mapping as IP address canonical hostname aliases, then verify the result with getent or resolvectl. Changes normally take effect immediately, although an individual application may retain an older cached result.

What the Ubuntu hosts file does

The Ubuntu hosts(5) manual describes /etc/hosts as “a simple text file that associates IP addresses with hostnames.” It is a local, static lookup table, not a DNS-zone editor. An entry affects name resolution on the Ubuntu machine where the file is stored; it does not publish a name for other computers on your network or on the internet.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When a program asks Ubuntu for a hostname, the system name-service stack can consult this file and return the address written there. With the usual Ubuntu resolver configuration, systemd-resolved reads the file locally. A matching hosts-file name is answered without sending that lookup to a DNS server. The mapping applies to address lookups; it does not provide other DNS record types such as MX records.

Back up the file before changing it

A misplaced character can make local services unreachable or cause commands that depend on the machine name to fail. Create a copy first:

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.
sudo cp /etc/hosts /etc/hosts.bak

The backup is in the same directory, so it is available even if the edited file contains an error. To restore it later, use:

sudo cp /etc/hosts.bak /etc/hosts

Check the permissions after editing. The file should remain owned by root and should not be made world-writable merely to avoid using sudo.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Understand the required line format

Each non-comment line contains an address first, the canonical hostname second, and optional aliases after that:

IP_address canonical_hostname [aliases...]

Separate fields with spaces or tabs. A # begins a comment; anything after it on that line is ignored. Hostnames can contain letters, numbers, hyphens, and periods, subject to the hostname rules documented in hosts(5). Do not put the hostname before the address.

Ubuntu’s standard entries

A typical desktop or server file resembles this:

127.0.0.1       localhost
127.0.1.1       myhost.example.test myhost
192.168.1.10    fileserver.example.test fileserver
::1             localhost ip6-localhost ip6-loopback
ff02::1         ip6-allnodes
ff02::2         ip6-allrouters
Line or address Purpose
127.0.0.1 localhost IPv4 loopback name for the local computer.
127.0.1.1 myhost.example.test myhost Common Ubuntu convention for the local machine’s hostname and optional short alias.
192.168.1.10 fileserver.example.test fileserver An example private-network server mapping; use the server’s actual address and names.
::1 localhost ip6-localhost ip6-loopback IPv6 loopback names.
ff02::1 and ff02::2 Common IPv6 multicast names for all nodes and all routers.

Keep the existing localhost and IPv6 lines intact unless you have a documented reason to change them. Removing or repurposing loopback names can break software that assumes they resolve locally.

Edit /etc/hosts safely

1. Open the file with a root-aware editor

The preferred approach is sudoedit, which opens a temporary copy in your configured editor and writes it back with the correct privileges:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
sudoedit /etc/hosts

If you specifically want Nano, run:

sudo nano /etc/hosts

Do not edit a copy in your home directory and assume it changes the system file. The saved file must be /etc/hosts itself.

2. Preserve the existing local entries

Before adding anything, identify the current 127.0.0.1, 127.0.1.1, and IPv6 lines. Ubuntu’s official example uses 127.0.1.1 for the machine’s fully qualified name in addition to the short name. Leave unrelated aliases on those lines unless you are deliberately changing the system hostname.

3. Add the mapping

For a server at 192.168.1.10, add one line such as:

192.168.1.10    fileserver.example.test fileserver

The first name is the canonical name for the address. The second is an alias, so both fileserver.example.test and fileserver resolve to 192.168.1.10 on this Ubuntu installation. Use one line for multiple names that intentionally share the same address; do not create contradictory lines for the same name.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a local development site, a loopback mapping is common:

127.0.0.1       app.example.test app

This sends both names to the local machine. It does not make the site reachable from another computer. To point a name at another host, use that host’s reachable IPv4 or IPv6 address instead.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

4. Save and exit

In Nano, press Ctrl+O, confirm the filename, then press Ctrl+X. With sudoedit, save and close the editor; the temporary file is copied back only if the editor exits successfully.

5. Verify the file and mapping

First inspect the resulting lines:

grep -v '^[[:space:]]*#' /etc/hosts

Then test through the system name-service path:

getent hosts fileserver
resolvectl query fileserver.example.test
ping -c 1 fileserver

getent hosts is a useful first test because it asks the configured name-service stack rather than reading the file in isolation. On systems using systemd-resolved, resolvectl query shows the resolver’s answer. A successful ping confirms that the name resolved and that an ICMP response was received; a failed ping does not by itself prove that the hosts entry is wrong because firewalls may block ICMP.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Examples for common configurations

One hostname with a short alias

10.0.0.25       printer.office.test printer

Both names resolve to the same address locally. Ensure that the address is stable; a DHCP lease change can make a static entry point to the wrong device.

Several names on one local service

192.168.1.20    git.office.test git source-control

Aliases are space-separated and remain on the same line as the canonical name.

An IPv6-only target

2001:db8:1234::20    service.example.test service

Use the actual IPv6 address assigned in your network. Do not substitute the documentation prefix above for a real production address.

Comments for maintenance

192.168.1.10    fileserver.example.test fileserver  # office NAS

Comments help future administrators understand why an entry exists. They are ignored by the resolver.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Changing Ubuntu’s system hostname

If you are renaming the Ubuntu machine itself, keep /etc/hostname and /etc/hosts consistent. Ubuntu guidance places the new name on the 127.0.1.1 line before applying the hostname change. For example, a machine currently using ubuntu can be prepared with:

127.0.1.1       ubuntu newname

Apply the hostname change with the normal hostname tool:

sudo hostnamectl set-hostname newname

After the change, edit the line so the new canonical name remains and the old alias is removed when it is no longer needed:

127.0.1.1       newname

Check both files:

cat /etc/hostname
getent hosts "$(hostname)"

The exact fully qualified name used in your environment may include a domain suffix. Keep the spelling and capitalization consistent in the hostname file, the 127.0.1.1 entry, certificates, service configuration, and automation that refers to the machine.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How /etc/hosts interacts with systemd-resolved and DNS

The hosts file supplies static local answers. It does not configure DNS servers, search domains, DHCP behavior, or network interfaces. Ubuntu Server documentation recommends using resolvectl and the systemd-resolved configuration for resolver settings rather than manually replacing /etc/resolv.conf.

systemd-resolved reads hosts-file mappings locally and immediately under its normal configuration. Those names are not sent to upstream DNS. Its documentation also states that localhost and localhost.localdomain are synthesized as 127.0.0.1 and ::1. Hosts-file support can be disabled with ReadEtcHosts=no; if that setting is present, entries in /etc/hosts will not be used by that resolver.

Do not use /etc/hosts to create mail routing, service-discovery, or other DNS record types. The mapping is an address-to-name association only. A name can resolve correctly with getent while an application that needs an MX, SRV, TXT, or other record still requires DNS.

Troubleshoot a mapping that does not work

The name returns no address

  • Confirm that the line is not commented out and that the address appears before the hostname.
  • Check for spelling differences between the command, /etc/hostname, and /etc/hosts. Hostname comparisons can be affected by exact spelling, so test the fully qualified and short forms separately.
  • Make sure there are no hidden characters or accidental punctuation. Display the file with line numbers if necessary: sudo nl -ba /etc/hosts.
  • Run getent hosts name. If it fails, the system name-service stack did not obtain an answer from the configured sources.

The wrong address is returned

  • Search for duplicate entries for the same hostname and remove or correct stale ones.
  • Verify that the address belongs to the intended machine and that a DHCP lease or network redesign has not changed it.
  • Test the exact name used by the application. A short alias and a fully qualified hostname can be separate entries.

One application still uses the old address

The hosts-file change normally takes effect without a reboot, but applications may cache name lookups independently. Close and restart only the affected program or service first. Browsers, language runtimes, containerized applications, and long-running daemons can each have their own cache or resolver behavior. If getent and resolvectl query show the new address, the remaining problem is likely inside that application or its network namespace rather than in the file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

sudo says it cannot resolve the host

This warning commonly means the machine’s current hostname does not resolve locally. Compare:

hostname
cat /etc/hostname
getent hosts "$(hostname)"

Ensure the hostname shown by hostname appears on the appropriate 127.0.1.1 line (or on another deliberate local address) and that /etc/hostname contains the same name. Correct the spelling, save the file, and run the getent test again. Do not “fix” the warning by deleting the localhost entries.

resolvectl does not reflect the entry

  • Check whether systemd-resolved is active and whether its configuration has ReadEtcHosts=no.
  • Use getent hosts name to test the complete name-service configuration even when resolvectl is unavailable or a different resolver is in use.
  • Inspect the exact file being used. A container, chroot, virtual machine, or separate network namespace can have its own /etc/hosts.

Ping fails after the name resolves

A resolved name proves only that an address was selected. Check reachability, routing, service ports, and firewall policy separately. Use a protocol-specific test such as the service’s client or a TCP connection test when ICMP is filtered.

Operational and security considerations

  • Limit edits to the mappings you actually need. A hosts entry overrides normal DNS behavior for that name on the local machine.
  • Review entries after moving a service, changing a DHCP reservation, or restoring a system image; stale addresses can silently redirect administrative commands and applications.
  • Do not copy an untrusted hosts file onto a server. A malicious entry can redirect software downloads, update endpoints, login portals, or internal services without changing the network’s DNS.
  • Use version control or a configuration-management system for fleets, while preserving file ownership, permissions, localhost lines, and machine-specific differences.
  • Keep a dated or clearly named backup before bulk changes. Restore the backup if a change causes name-resolution failures, then reapply entries one at a time.

Quick verification checklist

  1. Create a backup with sudo cp /etc/hosts /etc/hosts.bak.
  2. Edit with sudoedit /etc/hosts or sudo nano /etc/hosts.
  3. Retain 127.0.0.1 localhost, the IPv6 localhost line, and the existing multicast entries unless a documented configuration requires otherwise.
  4. Write new lines as address canonical-name alias, with spaces or tabs between fields.
  5. Confirm the address and spelling, then save the file.
  6. Run getent hosts name; on systemd-resolved systems also run resolvectl query name.
  7. Restart only an application that continues to use a cached result.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.