k8s上不同服务之间可以通过service的域名来互相访问。域名的解析是一般是通过在集群中的kube-dns来完成有时候,我们希望给运行在k8s上的Pod增加一些域名的解析(例如宿主机的主机名),但操作dns模块也不太方便,那么k8s上有没有想linux主机那样可以直接在host文件设置域名解析呢,容易想到的是,将域名记录到容器镜像的/etc/hosts文件,这样容器运行时就可以正确解析了。然而这样是不行的。k8s会管理这个文件,打到镜像里的文件实际并不会起作用。举个例子。

[root@master]# cat Dockerfile 

FROM nginx:1.0

RUN  echo "8.8.8.8 google.com" >> /etc/hosts 

EXPOSE 80

CMD ["/usr/local/nginx/sbin/nginx", "-g", "daemon off;"]

[root@master]# docker run -it testnginx /bin/bash

[root@8153d35a37e9 /]# cat /etc/hosts

127.0.0.1       localhost

::1     localhost ip6-localhost ip6-loopback

fe00::0 ip6-localnet

ff00::0 ip6-mcastprefix

ff02::1 ip6-allnodes

ff02::2 ip6-allrouters

172.17.0.5      8153d35a37e

显然在打镜像的时候配置hosts是不满足要求的,不过幸运的是k8s从1.7版本开始支持了 HostAliases 特性

[root@master test]# vim hostalias.yaml 

apiVersion: v1

kind: Pod

metadata:

  name: hostaliases-pod

spec:

  restartPolicy: Never

  hostAliases:

  – ip: "10.1.2.2"

    hostnames:

    – "mc.local"

    – "rabbitmq.local"

  – ip: "10.1.2.3"

    hostnames:

    – "redis.local"

    – "mq.local"

  containers:

  – name: cathosts

    image: busybox

    command:

    – cat

    args:

    – "/etc/hosts"                                                                                                                                                 

[root@mastertest]# kubectl apply -f hostalias.yaml 

Warning: kubectl apply should be used on resource created by either kubectl create –save-config or kubectl apply

pod "hostaliases-pod" configured

[root@master-168-32 test]# 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.244.1.162    hostaliases-pod

# Entries added by HostAliases.

10.1.2.2        mc.local

10.1.2.2        rabbitmq.local

10.1.2.3        redis.local

10.1.2.3        mq.local

在yaml配置文件中增加的几条记录都出现在 /etc/hosts 文件中了。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注