kubernetes可以通过.spec.hostAliases
字段添加主机别名,这个功能是在1.7.x以及以上版本提供的
查看默认的hosts文件
创建pod
[root@demo ~]# kubectl run nginx --image xxx/hub/nginx:20180808 --generator=run-pod/v1
pod "nginx" created
[root@test-master-113 ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 0/1 ContainerCreating 0 3s
[root@test-master-113 ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 0/1 ContainerCreating 0 5s
[root@test-master-113 ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 0/1 ContainerCreating 0 6s
[root@test-master-113 ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 0/1 ContainerCreating 0 7s
[root@test-master-113 ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 8s
[root@test-master-113 ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 10s
查看pod的hosts的信息
[root@demo ~]# 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
192.168.116.183 nginx
添加其他host的信息
使用HostAliases添加其他host信息
添加ip 127.0.0.1 对应的主机名为foo.local
和 bar.local
添加ip 10.1.2.3 对应的主机名为foo.remote
和 bar.remote
如下
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: harbor.enncloud.cn/hub/nginx:20180808
command:
- cat
args:
- "/etc/hosts"
查看日志
[root@demo qinzhao]# 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
192.168.141.26 hostaliases-pod
127.0.0.1 foo.local
127.0.0.1 bar.local
10.1.2.3 foo.remote
10.1.2.3 bar.remote
参考:add-entries-to-pod-etc-hosts-with-host-aliases