最近,给公司搭建的持续集成过程中,由于每次执行任务时都是新创建一个 Kubernetes Pod 执行的,在执行过程中经常出现 DNS 解析错误问题,如下:
stdout:
stderr: fatal: unable to access
'http://git.xxx.cn/mydlqcloud-xxxx/': Could not resolve host: git.xxxx.cn
经过排查物理机 DNS 和 CodeDNS 插件,都没找出问题所在,所以只能归咎于公司 DNS 服务器问题导致。无奈,没有能力要求修复与更改 NDS 服务器,只能想如果能手动配置镜像中的 Host 文件,让其直接解析域名到指定的 IP 地址,不要经过 DNS 服务器解析,那么这个问题就能够简单的迎刃而解。
经过一番查找 Kubernetes 中确实提供了能够配置 Docker 镜像中的 Host 的配置的字段 `hostAliases`,只要简单的配置就能轻松指定域名解析的 IP 地址,下面将介绍下如何配置。
这里配置一个用于示例的 Deployment 对象,为了后续测试时,能够执行部分命令,所以这里使用 CentOS 镜像。在 Deployment 配置中配置 Host 文件中添加 42.51.51.51
映射到 666.myit.icu
域名,Deployment 内容如下:
vim centos-deployment.yaml
kind: Deployment
apiVersion: apps/v1
metadata:
name: centos7
labels:
app: centos7
spec:
replicas: 1
selector:
matchLabels:
app: centos7
template:
metadata:
labels:
app: centos7
spec:
#-------------------------------------------
hostAliases: #配置hosts文件
- ip: "42.51.51.51" #配置解析的IP
hostnames:
- "666.myit.icu" #配置域名
#-------------------------------------------
containers:
- name: service-provider
image: centos:7.7.1908
command:
- "/bin/sh"
args:
- "-c"
- "while true; do sleep 999999; done"
部署到 Kubernetes 中:
$ kubectl apply -f centos-deployment.yaml
接下来将要进入刚刚部署的Deployment的Pod中,查看Hosts文件是否发生变化,以及是否能够按照Hosts文件中的配置进行解析。
查找部署的 CentOS 的 Pod
[root@master1 ~]#kubectl get pod | grep centos7
centos7-7fcdf4d875-q2hr6 1/1 Running 0 10m
[root@master1 ~]#kubectl exec centos7-7fcdf4d875-q2hr6 -it -- /bin/bash
[root@centos7-7fcdf4d875-q2hr6 /]# 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.244.4.24 centos7-7fcdf4d875-q2hr6
# Entries added by HostAliases.
42.51.51.51 666.myit.icu
可以看到配置信息 42.51.51.51 666.myit.icu
已经加入到镜像的hosts地址,说明配置已经生效。
接下来执行 Ping 命令访问对应域名,查看是否能按照我们配置解析出 IP 地址:
$ ping 666.myit.icu
[root@centos7-7fcdf4d875-q2hr6 /]# ping 666.myit.icu
PING 666.myit.icu (42.51.51.51) 56(84) bytes of data.
64 bytes from 666.myit.icu (42.51.51.51): icmp_seq=1 ttl=58 time=0.553 ms
64 bytes from 666.myit.icu (42.51.51.51): icmp_seq=2 ttl=58 time=0.454 ms
64 bytes from 666.myit.icu (42.51.51.51): icmp_seq=3 ttl=58 time=0.404 ms
64 bytes from 666.myit.icu (42.51.51.51): icmp_seq=4 ttl=58 time=0.396 ms
^C
--- 666.myit.icu ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3000ms
rtt min/avg/max/mdev = 0.396/0.451/0.553/0.067 ms
经过上面测试,在Kubernetes部署对象中,确实可以配置 hostAliases
参数,来加入我们自定义hosts配置,根据这一点,在发生DNS 解析问题时,通过此办法能够帮助我们解决部分问题。