Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 修改主機名永久生效三步驟:hostnamectl、/etc/hostname、/etc/hosts 同步修改

編輯:Linux 教學

修改 Linux 主機名需同步三個位置,重啟後永久生效。適用 RHEL/CentOS 7/8、Ubuntu 18.04+ (systemd 系統)。

步驟 1:使用 hostnamectl 立即生效 (不重啟)

hostnamectl set-hostname new-hostname
# 驗證
hostnamectl status
# 或
hostname
此命令同時更新 /etc/hostname 並通知 systemd-hostnamed 服務,當前 Shell 需重新登入或執行 bash 才會在提示字元顯示新名稱。

步驟 2:確認 /etc/hostname 內容

cat /etc/hostname
# 應只包含新主機名 (無域名),如:new-hostname

步驟 3:同步修改 /etc/hosts 解析本機名稱

vim /etc/hosts
# 將 127.0.0.1 及 ::1 後的舊主機名替換為新主機名
127.0.0.1   localhost localhost.localdomain new-hostname
::1         localhost localhost.localdomain new-hostname
關鍵:許多服務 (Postfix、MySQL、Hadoop、K8s) 啟動時會解析本機主機名,/etc/hosts 缺少對應會導致啟動失敗或效能下降。

驗證完整生效

reboot
# 重啟後
hostname
hostnamectl
cat /etc/hostname
cat /etc/hosts
ping -c 2 $(hostname)  # 應解析至 127.0.0.1

傳統 SysVinit 系統 (CentOS 6 等) 手動修改法

# 1. 修改 /etc/sysconfig/network
HOSTNAME=new-hostname
# 2. 修改 /etc/hosts (同上)
# 3. 臨時生效
hostname new-hostname
# 4. 重啟 network 服務或重啟主機
service network restart

常見問題

  • FQDN vs 短名:hostnamectl set-hostname 只接受短名;完整 FQDN 需在 /etc/hosts 映射。
  • 雲端實例:AWS/Azure/GCP/阿里雲實例首次啟動由 cloud-init 根據 metadata 設定主機名,手動修改後需確認 /etc/cloud/cloud.cfg 中 preserve_hostname: true 防止重開機被覆蓋。
  • Kubernetes:節點主機名變更需重新加入叢集 (kubeadm reset → join),因證書、kubelet 參數綁定主機名。
Copyright © Windows教程網 All Rights Reserved