很多场景下,不希望修改宿主机/etc/hosts或者DNS解析,此时就需要考虑为Pod设置单独的DNS解析,当然使用静态修改Host也有问题,就是无法动态解析,如果更换域名后就需要修改配置文件重建Pod。添加前请根据实际业务场景配置,考虑是否适合/etc/hosts的方式
hostAliases
hostAliases 是 Kubernetes 中的一项功能,用于在 Pod 中的 /etc/hosts 文件中添加自定义主机名与 IP 地址的映射。这个功能允许开发者为每个 Pod 手动定义主机名解析,而无需依赖外部 DNS 服务。
缺点
- hostAliases 仅对 Pod 内部有效,不会影响集群中的其他 Pod。
- 它只适用于静态的 IP 地址,无法自动处理动态 IP 变化。
- 无法通过 Kubernetes 的服务发现机制自动更新主机名映射。
配置方法
hostAliases配置也很简单,参考如下
为test.1.com添加1.1.1.1 IP解析
#在spec字段下配置如下参数
hostAliases:
- ip: "1.1.1.1"
hostnames:
- "test.1.com"
这里我使用官方提供的Pod文件进行演示,Deployment格式相同
apiVersion: v1
kind: Pod
metadata:
name: hostaliases-pod
spec:
restartPolicy: Never
hostAliases:
- ip: "192.168.21.98"
hostnames:
- "i4t.com"
- "frps.cn"
- ip: "192.168.21.10"
hostnames:
- "nginx.frps.cn"
containers:
- name: cat-hosts
image: busybox:1.28
command:
- cat
args:
- "/etc/hosts"
创建测试Pod
root@k8s-master-01:/tmp# kubectl apply -f pod.yaml
pod/hostaliases-pod created
查看Pod状态
root@k8s-master-01:/tmp# kubectl get pod |grep host
hostaliases-pod 0/1 Completed 0 57s
检查Pod文件hosts内容:
此时,Pod中/etc/hosts解析已经生效
root@k8s-master-01:/tmp# 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.0.0.136 hostaliases-pod
# Entries added by HostAliases.
192.168.21.98 i4t.com frps.cn
192.168.21.10 nginx.frps.cn

