Kubernetes 使用HostAliases向Pod /etc/hosts文件添加條目

2022-06-20 09:49 更新

使用 HostAliases 向 Pod /etc/hosts 文件添加條目

當(dāng) DNS 配置以及其它選項不合理的時候,通過向 Pod 的 /etc/hosts 文件中添加條目, 可以在 Pod 級別覆蓋對主機(jī)名的解析。你可以通過 PodSpec 的 HostAliases 字段來添加這些自定義條目。

建議通過使用 HostAliases 來進(jìn)行修改,因為該文件由 Kubelet 管理,并且 可以在 Pod 創(chuàng)建/重啟過程中被重寫。

默認(rèn) hosts 文件內(nèi)容 

讓我們從一個 Nginx Pod 開始,該 Pod 被分配一個 IP:

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

主機(jī)文件的內(nèi)容如下所示:

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

默認(rèn)情況下,hosts 文件只包含 IPv4 和 IPv6 的樣板內(nèi)容,像 ?localhost ?和主機(jī)名稱。

通過 HostAliases 增加額外條目

除了默認(rèn)的樣板內(nèi)容,我們可以向 hosts 文件添加額外的條目。 例如,要將 ?foo.local?、?bar.local? 解析為 ?127.0.0.1?, 將 ?foo.remote?、 ?bar.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 地址和狀態(tài):

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 文件的內(nèi)容看起來類似如下這樣:

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 ?文件,以防止容器運(yùn)行時在容器已經(jīng)啟動后修改文件。 由于歷史原因,Kubernetes 總是使用 Docker Engine 作為其容器運(yùn)行時,而 Docker Engine 將在容器啟動后修改 ?/etc/hosts? 文件。

當(dāng)前的 Kubernetes 可以使用多種容器運(yùn)行時;即便如此,kubelet 管理在每個容器中創(chuàng)建 hosts文件, 以便你使用任何容器運(yùn)行時運(yùn)行容器時,結(jié)果都符合預(yù)期。

注意:
請避免手工更改容器內(nèi)的 hosts 文件內(nèi)容。
如果你對 hosts 文件做了手工修改,這些修改都會在容器退出時丟失。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號