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

Last updated: 2020-11-09

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. How do I make the new hostname to persist?

Short description

To be sure that the hostname persists when rebooting or stopping and starting your instance, 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:

Changing the system hostname

How do I assign a static hostname to an Amazon EC2 instance running RHEL 5 or 6, CentOS 5 or 6, or Amazon Linux?

How do I assign a static hostname to an Amazon EC2 instance running SLES?

How do I assign a static hostname to an Amazon EC2 instance running RHEL 7 or CentOS 7?

Resolution

1.     Use vim 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:

127.0.0.1 localhost persistent-hostname

Note: You might have to create an entry for localhost if the /etc/hosts file on your EC2 instance doesn't have 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, 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 making 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.

hostname

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, you must run these steps again.


Did this article help?


Do you need billing or technical support?