使用 HostAliases 將條目新增至 Pod /etc/hosts

將條目新增至 Pod 的 /etc/hosts 檔案,可在 DNS 和其他選項不適用時提供主機名稱解析的 Pod 層級覆寫。您可以使用 PodSpec 中的 HostAliases 欄位新增這些自訂條目。

Kubernetes 專案建議使用 hostAliases 欄位(Pod 的 .spec 的一部分)修改 DNS 組態,而不是使用初始化容器或其他方式直接編輯 /etc/hosts。以其他方式進行的變更可能會在 Pod 建立或重新啟動期間被 kubelet 覆寫。

預設 hosts 檔案內容

啟動已指派 Pod IP 的 Nginx Pod

kubectl run nginx --image nginx
pod/nginx created

檢查 Pod IP

kubectl get pods --output=wide
NAME     READY     STATUS    RESTARTS   AGE    IP           NODE
nginx    1/1       Running   0          13s    10.200.0.4   worker0

hosts 檔案內容看起來會像這樣

kubectl exec nginx -- cat /etc/hosts
# Kubernetes-managed hosts file.
127.0.0.1	localhost
::1	localhost ip6-localhost ip6-loopback
fe00::0	ip6-localnet
fe00::0	ip6-mcastprefix
fe00::1	ip6-allnodes
fe00::2	ip6-allrouters
10.200.0.4	nginx

依預設,hosts 檔案僅包含 IPv4 和 IPv6 樣板,例如 localhost 及其本身的主機名稱。

使用 hostAliases 新增其他條目

除了預設樣板之外,您還可以將其他條目新增至 hosts 檔案。例如:若要將 foo.localbar.local 解析為 127.0.0.1,並將 foo.remotebar.remote 解析為 10.1.2.3,您可以為 .spec.hostAliases 下的 Pod 設定 HostAliases

apiVersion: v1
kind: Pod
metadata:
  name: hostaliases-pod
spec:
  restartPolicy: Never
  hostAliases:
  - ip: "127.0.0.1"
    hostnames:
    - "foo.local"
    - "bar.local"
  - ip: "10.1.2.3"
    hostnames:
    - "foo.remote"
    - "bar.remote"
  containers:
  - name: cat-hosts
    image: busybox:1.28
    command:
    - cat
    args:
    - "/etc/hosts"

您可以執行下列命令以使用該組態啟動 Pod

kubectl apply -f https://k8s.io/examples/service/networking/hostaliases-pod.yaml
pod/hostaliases-pod created

檢查 Pod 的詳細資訊以查看其 IPv4 位址及其狀態

kubectl get pod --output=wide
NAME                           READY     STATUS      RESTARTS   AGE       IP              NODE
hostaliases-pod                0/1       Completed   0          6s        10.200.0.5      worker0

hosts 檔案內容看起來像這樣

kubectl logs hostaliases-pod
# Kubernetes-managed hosts file.
127.0.0.1	localhost
::1	localhost ip6-localhost ip6-loopback
fe00::0	ip6-localnet
fe00::0	ip6-mcastprefix
fe00::1	ip6-allnodes
fe00::2	ip6-allrouters
10.200.0.5	hostaliases-pod

# Entries added by HostAliases.
127.0.0.1	foo.local	bar.local
10.1.2.3	foo.remote	bar.remote

底部有額外指定的條目。

為什麼 kubelet 管理 hosts 檔案?

kubelet 管理 Pod 的每個容器的 hosts 檔案,以防止容器執行期在容器已啟動後修改檔案。從歷史上看,Kubernetes 始終使用 Docker Engine 作為其容器執行期,而 Docker Engine 然後會在每個容器啟動後修改 /etc/hosts 檔案。

目前的 Kubernetes 可以使用多種容器執行期;即便如此,kubelet 仍會管理每個容器內的 hosts 檔案,以便無論您使用哪種容器執行期,結果都能如預期。

上次修改時間:2024 年 10 月 03 日下午 4:50 PST:移除重複資訊 (05c1f011d4)