Ongoing service disruptions
For the most recent update on ongoing service disruptions affecting the AWS Middle East (UAE) Region (ME-CENTRAL-1), refer to the AWS Health Dashboard. For information on AWS Service migration, see How do I migrate my services to another region?
如何为 EC2 Linux 实例分配静态主机名?
我更改了 Amazon Elastic Compute Cloud (Amazon EC2) 实例的主机名。但是,当我重启实例,或停止后重启实例时,主机名会变回原始主机名。
解决方法
**重要事项:**在更新实例之前,请为您的实例创建 Amazon Elastic Block Store (Amazon EBS) 支持的亚马逊机器映像 (AMI)。
检查现有的实例主机名
完成以下步骤:
-
要切换到根用户,请运行以下命令:
sudo su - -
要检查实例主机名,请运行以下命令:
hostnamectl
配置静态主机名
为您运行的操作系统 (OS) 配置静态主机名。
AL2 或 Al2023
对于 Amazon Linux 2 (AL2) 或 Amazon Linux 2023 (AL2023),请完成以下步骤:
-
要打开 ** /etc/cloud/cloud.cfg**,请运行以下命令:
vim /etc/cloud/cloud.cfg -
查看 preserve_hostname 属性。如果其值为 false,请将该值更新为 true。
示例:preserve_hostname: true**注意:**如果文件没有 preserve_hostname 属性,则将该属性添加到文件中并将该值设置为 true。
-
要设置静态主机名,请运行以下命令:
hostnamectl set-hostname persistent-hostname**注意:**将 persistent-hostname 替换为您的主机名。
Ubuntu
对于 Ubuntu,请完成以下步骤:
-
要设置静态主机名,请完成以下步骤:
hostnamectl set-hostname --static persistent-hostname**注意:**将 persistent-hostname 替换为您的主机名。
-
要打开 /etc/hosts,请运行以下命令:
vim /etc/hosts -
在文件中输入以下行:
localhost persistent-hostname**注意:**将 persistent-hostname 替换为您的主机名。
-
如果您的 EC2 实例使用 IPv6,还需输入以下配置数据:
::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 -
要打开 ** /etc/cloud/cloud.cfg**,请运行以下命令:
vim /etc/cloud/cloud.cfg -
查看 preserve_hostname 属性。如果其值为 false,请将该值更新为 true。
示例:preserve_hostname: true
RHEL 或 CentOS 7、8 和 9
对于 Red Hat Enterprise Linux (RHEL) 或 CentOS 7、8 和 9,请完成以下步骤:
-
要设置静态主机名,请运行以下命令:
hostnamectl set-hostname --static persistent-hostname**注意:**将 persistent-hostname 替换为您的主机名。
-
对于 RHEL 7.3 或更早版本,运行以下命令打开 /etc/cloud/cloud.cfg:
vi /etc/cloud/cloud.cfg -
查看 preserve_hostname 属性。如果该值为 false,请将该值更新为 true。
示例:preserve_hostname: true
SUSE Linux
对于 SUSE Linux Enterprise Server (SLES),请完成以下步骤:
-
要设置主机名,请根据您的 SLES 版本运行以下命令。
SLES 11:hostname persistent-hostnameSLES 12 和 15:
hostnamectl set-hostname persistent-hostname**注意:**将 persistent-hostname 替换为您的主机名。
-
运行以下命令使用您的主机名更新 /etc/HOSTNAME 文件:
echo "persistent-hostname" > /etc/HOSTNAME**注意:**将 HOSTNAME 替换为您的主机名。
-
要打开 /etc/hosts,请运行以下命令:
vim /etc/hosts -
根据您的 SLES 版本在文件中输入以下行,并将其替换为您的主机名。
SLES 11:127.0.0.1 localhost persistent-hostnameSLES 12 和 15:
127.0.0.1 localhost persistent-hostname**注意:**将 persistent-hostname 替换为您的主机名。
-
要打开 /etc/cloud/cloud.cfg 文件,请运行以下命令:
vim /etc/cloud/cloud.cfg -
在文件中输入以下行:
preserve_hostname: true
实施更改
完成以下步骤:
-
要重启实例,请运行以下命令:
reboot -
要验证新的主机名,请运行以下命令:
hostnamectl
对您的问题进行故障排除
如果您在重启后遇到意外的主机名更改,请执行以下操作:
- 查看位于 /var/log/cloud-init.log 和 /var/log/syslog 的系统日志,以了解有关主机名更改的条目。
- 如果您安装了影响 /etc/hosts、主机名文件或主机名实用程序的系统更新,请再次完成前面的解析步骤。
- 验证 /etc/cloud/cloud.cfg 文件中的 preserve_hostname 设置是否为 true。
