萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux /etc/hosts 檔案完整解析:靜態域名解析、優先級與應用場景

hosts 檔案定義與角色

/etc/hosts:靜態查表檔案,提供 IP 位址與主機名/域名的直接映射,ASCII 文字格式,優先級高於 DNS 服務。

解析優先級順序

DNS 快取 > /etc/hosts > DNS 服務器查詢

應用程式解析流程:

  1. 檢查本地 DNS 快取
  2. 查詢 /etc/hosts
  3. 發送 DNS 查詢至 /etc/resolv.conf 指定的名稱伺服器
  4. /etc/nsswitch.conf 中 hosts: files dns 確定順序

檔案格式規範

IP地址  主機名/域名  [別名...]
# 註解以 # 開頭

標準範例

127.0.0.1       localhost localhost.localdomain
::1             localhost6 localhost6.localdomain6
192.168.1.10    webserver web
192.168.1.20    dbserver db
10.0.0.5        backup.example.com backup

核心應用場景

1. 開發測試環境域名模擬

# 本地開發對應線上域名
127.0.0.1  api.example.com
127.0.0.1  www.example.com
192.168.1.50  staging.example.com

2. 內網服務別名簡化

# 避免記憶 IP
10.10.20.5  gitlab ci registry monitoring
10.10.20.10 k8s-master k8s-node1 k8s-node2

3. 阻擋惡意/廣告域名

0.0.0.0  ads.google.com
0.0.0.0  tracking.facebook.com
127.0.0.1  malware-site.com

4. 線下環境網路隔離測試

# 將外部服務導向內部測試實例
192.168.100.10  payment-gateway.example.com
192.168.100.11  sms-provider.example.com

5. Kubernetes/容器內部解析

# Pod 內 /etc/hosts 自動注入
127.0.0.1  localhost
::1  localhost
10.244.1.5  mypod  # Pod IP
# Headless Service 由 CoreDNS 處理,不在 hosts

實戰驗證範例

修改百度解析指向本機

echo "127.0.0.1 www.baidu.com" >> /etc/hosts

Ping 驗證效果

ping www.baidu.com
PING www.baidu.com (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.023 ms
...

進階技巧與注意事項

IPv6 支援

::1  localhost ipv6-localhost
fe80::1%lo0  localhost
2001:db8::1  ipv6-server

多主機名對應同一 IP

192.168.1.10  app1.example.com app2.example.com api.example.com

長主機名處理

# 每行長度建議 < 255 字元,超長請換行
192.168.1.10  very-long-hostname-that-exceeds-normal-length.example.com \
              another-long-name.example.com

性能影響

  • 檔案過大(>1000 行)會略微增加解析延遲
  • 建議配合 dnsmasq 或 systemd-resolved 快取
  • 容器化環境建議使用 CoreDNS/Corefile 管理

自動化管理工具

  • ansible.builtin.lineinfile:Ansible 管理 hosts
  • hostess:Go 寫入的 hosts 管理 CLI
  • switchhosts:跨平台 GUI 管理工具

故障排除

copyright © 萬盛學電腦網 all rights reserved
現象原因解決
修改不生效DNS 快取/應用程式快取systemd-resolve --flush-caches、重啟應用、nscd -i hosts
容器內不生效容器有獨立 /etc/hosts用 --add-host 或修改映像
權限拒絕非 root 編輯sudo vim /etc/hosts
語法錯誤導致解析異常格式不符、編碼問題檢查編碼為 UTF-8/ASCII,無 BOM