代码改变世界

定义pod的hosts文件(HostAliases)

2022-08-20 12:36  假面Wilson  阅读(292)  评论(0编辑  收藏  举报

通过HostAliases 向 Pod /etc/hosts 文件添加条目

当 DNS 配置以及其它选项不合理的时候,通过向 Pod 的 /etc/hosts 文件中添加条目, 可以在 Pod 级别覆盖对主机名的解析。你可以通过 PodSpec 的 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
    command:
    - cat
    args:
    - "/etc/hosts"

进入POD 查看 Hosts

kubectl exec -ti {pod} -n {namespace} --kubeconfig {kubeconfig}  -- /bin/sh

cat /etc/hosts

pod打印/etc/hosts文件,多了以下内容

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

避免手动去修改/etc/hosts文件,通过HostAliases进行修改,因为该文件由 Kubelet 管理,并且 可以在 Pod 创建/重启过程中被重写