k8s 自定义pod hosts的几种方法

日常中我们可能会碰到不少关于自定义pod hosts的场景,对于不同的k8s 版本处理的不一样的
以下整理一些参考方法

自定义coredns

自定义coredns 可以直接让解析的域名使用coredns 处理,好处是可以全局生效,不好的地方就是全局可能会影响其他不需要自定义hosts的
扩展coredns 的方法就比较多了,可以基于dns 的转发以及直接配置coredns 的hosts
hosts 模式参考

. {
    hosts example.hosts example.org example.net {
        fallthrough
    }
}

对于k8s 小于1.7 版本的

可以基于声明周期钩子,添加hosts 文件
参考
yaml 定义,添加如下

lifecycle:
        postStart:
          exec:
            command: ["/bin/sh", "-c", "echo <ip>  <domain>  >> /etc/hosts"]

对于比较多的,我们可以直接使用文件配置,格式和hosts 一致

对于大于等于1.7 版本的

使用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:1.28
    command:
    - cat
    args:
    - "/etc/hosts"

参考资料

https://kubernetes.io/docs/tasks/network/customize-hosts-file-for-pods/
https://coredns.io/plugins/hosts/

posted on   荣锋亮  阅读(1921)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2020-06-16 使用openresty+ xip 服务暴露k8s 部署的spring cloud 服务为外部可访问的地址
2019-06-16 rustup 使用
2016-06-16 Oboe 提升web 用户体验以及性能

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示