October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk11 min

How to Set the Hostname on a Linux VPS (/etc/hosts and /etc/hostname)

A practical guide to renaming a Linux VPS permanently, mapping its FQDN and short name in /etc/hosts, verifying the result, and preventing cloud-init or DNS confusion.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To give a Linux VPS a persistent name, set its static hostname with sudo hostnamectl set-hostname web-01.example.com, then make /etc/hosts map the VPS address to that fully qualified domain name (FQDN) and its short name. Verify with hostnamectl status, hostname -f, and getent hosts. The hostname change is local; it does not create a public DNS record.

Fast procedure

On a systemd-based VPS, replace the example name and address with your own values:

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.
  1. Choose a DNS-compatible name, such as web-01 or web-01.example.com. Keep the static name within Linux’s 64-character limit and use letters, numbers, hyphens, and dots in DNS-style form.
  2. Inspect the current state with hostnamectl status, hostname, cat /etc/hostname, and getent hosts "$(hostname)".
  3. Set the persistent and running hostname: sudo hostnamectl set-hostname web-01.example.com.
  4. Edit /etc/hosts so the local address resolves to the FQDN first and the short name second. For a static IPv4 address, use a line such as 203.0.113.10 web-01.example.com web-01. For a Debian-style DHCP image, the local line may instead be 127.0.1.1 web-01.example.com web-01.
  5. Keep the existing 127.0.0.1 localhost and IPv6 localhost entries.
  6. Confirm the result with hostname, hostname -f, cat /etc/hostname, and getent hosts web-01.example.com. A reboot is normally unnecessary.

If the provider or cloud-init changes the name again after reboot, inspect that image’s initialization policy; provider automation is separate from the generic systemd behavior described here.

What the hostname files and commands actually do

/etc/hostname: the persistent local name

/etc/hostname is the local hostname configuration file. It should contain one newline-terminated string, normally just the intended static hostname. During boot, systemd reads this file and applies the value with the Linux sethostname(2) system call. A typical file therefore contains either web-01 or web-01.example.com on one line, with no address, aliases, or comments.

#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.

Editing this file alone changes what will be read at the next boot, but it does not reliably update the currently running hostname on every init system. On a systemd distribution, hostnamectl set-hostname is the safer one-command operation because it writes the persistent value and applies it immediately.

/etc/hosts: local name resolution

/etc/hosts is a local name-resolution database. It lets programs on the VPS translate a name into an address without asking public DNS. For the machine’s own identity, the usual order is the address, the FQDN, and then the short hostname:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
203.0.113.10 web-01.example.com web-01

The order matters for software that chooses the first canonical name returned by a lookup. Keep the FQDN first when you want hostname -f and local libraries to report that name.

This file does not publish an Internet DNS record. Remote clients will not resolve web-01.example.com because you edited /etc/hosts on one VPS; an authoritative DNS A or AAAA record must be created separately with the DNS service for the domain.

hostnamectl and the three hostname types

hostnamectl is systemd’s interface for viewing and changing hostnames. It distinguishes:

  • Static: the persistent value, normally stored in /etc/hostname.
  • Transient: a value supplied by network configuration, DHCP, or another runtime mechanism.
  • Pretty: an optional human-readable label that is not used as the machine’s DNS-style identity.

A valid static hostname normally takes precedence over a transient one. An image policy can nevertheless rewrite files or settings after boot, so persistence should be checked after the next planned restart.

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

Choose a short hostname or an FQDN

Both forms can be valid static hostnames. The right choice depends on the software and automation that will consume the value, not on whether one form is universally better.

Static value Advantages Check before choosing
web-01 One DNS-style label; conservative choice for software that expects a single host label and simple inventory names. Make sure local and public DNS, certificates, monitoring, and provider automation do not require the domain suffix.
web-01.example.com Self-describing FQDN; useful when services, logs, certificates, or administration routinely use the domain name. Ensure /etc/hosts maps the FQDN and short alias, and create a public DNS record separately if Internet clients must resolve it.

Use a stable name rather than an address-based label that will become misleading after a rebuild. Avoid spaces and arbitrary punctuation. Systemd documents DNS-style characters and a 64-character Linux limit for static and transient names. A single short label is the most conservative content for /etc/hostname; an FQDN is appropriate when the surrounding software is designed around it.

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.

Inspect the current state before changing anything

Run these commands as the current user; only the later write operations require root privileges:

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

Compare the results instead of assuming they already agree. hostname shows the current kernel hostname. cat /etc/hostname shows the persistent file. hostnamectl status displays static, transient, pretty, and related system information. getent hosts asks the system’s configured name-service stack to resolve a name, which reveals whether the current identity has a usable local mapping.

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

Record the VPS’s local addresses before editing /etc/hosts. Use the address assigned to the interface for a static-address mapping, and do not replace localhost entries merely because the server has a new name. If the provider presents a DHCP-style image, determine whether it already uses a 127.0.1.1 hostname line.

Set the hostname with systemd

On Debian, Ubuntu, Red Hat Enterprise Linux, and other common systemd-based VPS images, the documented command is:

sudo hostnamectl set-hostname web-01.example.com

The command validates the static name, writes /etc/hostname, and applies the running hostname. It does not edit /etc/hosts, create DNS records, rename files, or update application configuration. Those tasks must be handled separately.

To set only a short hostname, use the same command with the short value:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo hostnamectl set-hostname web-01

Do not put a trailing space, address, or alias in the argument. The hostname is a name, not an /etc/hosts line.

Make the local mapping in /etc/hosts

Open the file with a root-capable editor, for example:

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
sudoedit /etc/hosts

Retain the existing localhost records and add or correct the line that represents this VPS. Which address belongs on that line depends on how the image and network are configured.

Static IPv4 address

When the VPS has a stable private or public IPv4 address assigned to its interface, map that address to the FQDN and short alias:

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.
203.0.113.10 web-01.example.com web-01

Replace 203.0.113.10 with the actual local address. The example address is documentation-only and must not be copied as a real server address.

Debian-style DHCP mapping

Debian documents a common arrangement for hosts whose address is supplied dynamically:

127.0.1.1 web-01.example.com web-01

This is a local identity mapping, not a claim that the VPS’s network interface owns the loopback address. Use the convention already established by the image and its distribution documentation rather than adding a second, conflicting identity line.

IPv6 and localhost entries

Preserve the existing IPv6 localhost records, commonly including ::1 localhost with any existing aliases. Do not delete or merge them into the IPv4 hostname line. If the VPS has a stable IPv6 address and applications need the host’s FQDN to resolve over IPv6 locally, add a separate IPv6 mapping in the same address–FQDN–short-name order, following the image’s existing style.

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

Formatting rules

Each non-comment line consists of an address followed by one or more names separated by spaces or tabs. Put the canonical FQDN first, then the short alias. Comments begin with #. Do not place a URL, protocol, port, or slash in a hostname entry.

Verify the change without rebooting

Run the complete verification set:

hostnamectl status
hostname
hostname -f
cat /etc/hostname
getent hosts web-01.example.com
getent hosts web-01
  • hostnamectl status should show the intended static value.
  • hostname should print the running kernel hostname.
  • hostname -f should return the FQDN when the local mapping and resolver order provide one.
  • cat /etc/hostname should show exactly the persistent name, followed by its newline.
  • getent hosts should return the expected address and name instead of an empty result or an unrelated address.

These checks exercise different layers: the running kernel value, the persistent file, and the resolver path used by applications. A successful hostnamectl command does not prove that /etc/hosts is correct, so perform all of them.

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.

Manual fallback when hostnamectl is unavailable

Minimal images, non-systemd distributions, or restricted rescue environments may not provide hostnamectl. In that case:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Edit /etc/hostname as root and leave exactly the intended name on one line.
  2. Edit /etc/hosts so the correct local address maps to the FQDN and short name.
  3. Apply the running value with the legacy command if it is available: sudo hostname web-01.example.com.
  4. If that command is unavailable or the init system will not accept the change, reboot so the init system reads /etc/hostname.
  5. Run the same verification commands after applying the value.

The exact runtime command varies by init system. Do not assume that a systemd command exists on a non-systemd image, and do not treat a successful file edit as proof that the running process hostname has changed.

Distribution and VPS image behavior

Debian and Ubuntu use the same basic /etc/hostname format and boot behavior described above. Red Hat Enterprise Linux also documents hostnamectl set-hostname and persistence in /etc/hostname. This alignment makes the procedure portable across common systemd VPS images.

The part that is not portable is provider automation. Cloud-init, DHCP clients, NetworkManager, startup scripts, and image-specific agents can supply transient names or rewrite configuration. A valid static hostname usually wins over a transient value, but an image policy may still regenerate /etc/hostname or related settings on boot. If the value changes after a restart, inspect the image’s cloud-init and network initialization configuration rather than repeatedly editing the same files.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why “sudo: unable to resolve host” appears after a rename

The warning means the hostname used by the local command cannot be resolved through the VPS’s configured name-service path. It does not necessarily mean the rename failed. The common sequence is:

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.
  1. hostnamectl changes the running and static hostname.
  2. /etc/hosts still contains the old name, or has no line for the new one.
  3. sudo and other programs try to resolve the new hostname and print an error.

Fix the mapping rather than changing the hostname back. Ensure the exact FQDN and short name printed by hostname appear on the same local-address line in /etc/hosts, with the FQDN first. Then test:

hostname
hostname -f
getent hosts "$(hostname)"
sudo -v

If getent still returns nothing, check for spelling, hidden characters, duplicate conflicting lines, an incorrect address, or a resolver configuration that bypasses the expected hosts database. The warning can persist until the file is corrected; a reboot is not the normal remedy.

Other failure modes and fixes

The name reverts after reboot

Check whether cloud-init, DHCP, NetworkManager, or a provider startup script owns the hostname. Compare hostnamectl status immediately after boot with cat /etc/hostname. If both have been rewritten, modify the image’s initialization policy or disable the relevant hostname update according to that image’s documentation. Do not assume a generic systemd setting can override provider policy.

hostname -f prints the short name, an error, or an unexpected domain

hostname -f depends on resolver results, not only on /etc/hostname. Check that the FQDN appears on the local-address line, that it precedes the short alias, and that no stale line maps the same address to a different canonical name. Test both names with getent hosts.

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

The command rejects the hostname

Remove spaces, underscores, slashes, punctuation not accepted in DNS-style names, and trailing whitespace. Keep the name within 64 characters. If an application requires a particular naming convention, satisfy that application while remaining within valid static-hostname syntax.

Applications still display the old name

Some long-running services read the hostname only at startup or cache it in their own configuration. Confirm the kernel value first with hostname, then inspect the service’s configuration and restart only the affected service when its documentation requires it. Renaming the operating-system host does not automatically rename certificates, database identifiers, cluster membership, monitoring entries, or shell prompts.

Local resolution works but remote clients cannot connect by name

That is expected when only /etc/hosts was changed. Add the required A record for IPv4 and/or AAAA record for IPv6 at the authoritative DNS provider for the domain, wait for the record’s normal propagation and caching behavior, and test from a remote network. The VPS’s local hosts file has no authority outside that machine.

Choosing between hostnamectl and direct file editing

Method Runtime effect Persistent effect Main risk
hostnamectl set-hostname NAME Applies immediately on systemd systems. Writes the static value to /etc/hostname. Does not update /etc/hosts or provider automation.
Edit /etc/hostname only May not change the current kernel hostname until a separate command or reboot. Sets what systemd will read at boot. Leaves the running value and local resolver mapping inconsistent.
Edit both files and run legacy hostname Can work on non-systemd images where the legacy command exists. Persists through the edited file. Behavior and syntax vary by init system; easy to omit a required mapping.

For a normal systemd VPS, use hostnamectl and then edit /etc/hosts. Reserve the manual path for images where the documented systemd interface is unavailable.

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

Automating the change safely

Configuration management should make the operation idempotent: running it again with the same desired name should not create duplicate lines or alternate spellings. A safe automation sequence is:

  1. Read the desired hostname from one controlled variable.
  2. Validate that it contains only approved DNS-style characters and is no longer than 64 characters.
  3. Run hostnamectl set-hostname when systemd is present.
  4. Render the intended /etc/hostname content as one newline-terminated line.
  5. Manage one authoritative /etc/hosts line for the chosen address, FQDN, and short alias while preserving localhost records.
  6. Run hostname -f and getent hosts as post-change tests.
  7. Check again after a reboot or image refresh if cloud-init or provider automation is enabled.

Do not blindly append a new line on every run. Duplicate mappings can make resolver results depend on line order and can hide an old hostname that still appears in logs or administrative warnings.

Changing the name back or rolling out a replacement

To restore a previous name, repeat the same process with the old value:

sudo hostnamectl set-hostname old-name.example.com
sudoedit /etc/hosts

Update the corresponding FQDN and short alias in /etc/hosts, then rerun every verification command. If the server is part of a cluster, certificate system, monitoring platform, inventory, or backup policy, coordinate those external records before the change so the operating-system rename does not create a second, unrelated identity.

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

Final operational checklist

  • The chosen name is DNS-compatible and no longer than 64 characters.
  • hostnamectl status shows the intended static value.
  • /etc/hostname contains one exact, newline-terminated name.
  • /etc/hosts maps the local address to FQDN first and short name second.
  • Localhost IPv4 and IPv6 entries remain intact.
  • hostname, hostname -f, and getent hosts return the expected values.
  • Public DNS records were changed separately if outside clients need the FQDN.
  • Cloud-init, DHCP, NetworkManager, and provider policies have been checked for overwrite behavior.
  • Dependent services and external systems have been updated where they cache or validate the old hostname.

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.

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
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

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.