How do I assign a static hostname to an Amazon EC2 instance that runs Ubuntu Linux?

3 minute read

I changed the hostname of my Amazon Elastic Compute Cloud (Amazon EC2) instance. However, when I reboot or stop and then restart the instance, the hostname changes back to the original hostname.

Short description

Verify that the hostname persists when you reboot or stop and start your instance. To do this, add the hostname to the appropriate configuration files on your instance.

Note: The following steps apply to Ubuntu Linux. For instructions that apply to other distributions, see one of the following resources:


  1. Run the vim command to open the /etc/hosts file:

    sudo vim /etc/hosts
  2. Update the /etc/hosts file to include your persistent hostname for localhost, similar to the following example: localhost persistent-hostname

    Note: If the /etc/hosts file on your EC2 instance doesn't have an entry for localhost, then you might have to create an entry for it.

    For more information about the hosts file on Ubuntu, see the Ubuntu 18.04 hosts file manpage.

  3. If your EC2 instance uses IPv6, then add the following configuration data:

    ::1 ip6-localhost ip6-loopback
      fe00::0 ip6-localnet
      ff00::0 ip6-mcastprefix
      ff02::1 ip6-allnodes
      ff02::2 ip6-allrouters
      ff02::3 ip6-allhosts
  4. Save and exit the vim editor.

    Note: After you make this change, press SHIFT+:[colon] to open a new command entry box in the vim editor. Type wq, and then press Enter to save changes and exit vim. Or, use Shift + ZZ to save and close the file.

  5. Run the hostnamectl command and specify the new hostname. Replace the persistent-hostname with the new hostname:

    sudo hostnamectl set-hostname persistent-hostname
  6. After you start or reboot the EC2 instance, run the Linux hostname command without any parameters to verify that the hostname change persisted:


    The command returns the new hostname.

    Note: If you install any system updates that affect the /etc/hosts file, the hostname file, or the hostname utility, then you must run these steps again.

Related information

Change the hostname of your Amazon Linux instance

AWS OFFICIALUpdated 7 months ago