/etc/hosts:靜態查表檔案,提供 IP 位址與主機名/域名的直接映射,ASCII 文字格式,優先級高於 DNS 服務。
DNS 快取 > /etc/hosts > DNS 服務器查詢
應用程式解析流程:
/etc/hosts/etc/resolv.conf 指定的名稱伺服器/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
# 本地開發對應線上域名
127.0.0.1 api.example.com
127.0.0.1 www.example.com
192.168.1.50 staging.example.com
# 避免記憶 IP
10.10.20.5 gitlab ci registry monitoring
10.10.20.10 k8s-master k8s-node1 k8s-node2
0.0.0.0 ads.google.com
0.0.0.0 tracking.facebook.com
127.0.0.1 malware-site.com
# 將外部服務導向內部測試實例
192.168.100.10 payment-gateway.example.com
192.168.100.11 sms-provider.example.com
# 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 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
...

::1 localhost ipv6-localhost
fe80::1%lo0 localhost
2001:db8::1 ipv6-server
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
dnsmasq 或 systemd-resolved 快取ansible.builtin.lineinfile:Ansible 管理 hostshostess:Go 寫入的 hosts 管理 CLIswitchhosts:跨平台 GUI 管理工具| 現象 | 原因 | 解決 |
|---|---|---|
| 修改不生效 | DNS 快取/應用程式快取 | systemd-resolve --flush-caches、重啟應用、nscd -i hosts |
| 容器內不生效 | 容器有獨立 /etc/hosts | 用 --add-host 或修改映像 |
| 權限拒絕 | 非 root 編輯 | sudo vim /etc/hosts |
| 語法錯誤導致解析異常 | 格式不符、編碼問題 | 檢查編碼為 UTF-8/ASCII,無 BOM |