![](/img/trans.png)
[英]How to make host interfaces, including cni* accessible in kubernetes privileged pods?
[英]How to add custom host entries to kubernetes Pods?
我的应用程序通过主机名与某些服务通信。 将我的应用程序作为 docker 容器运行时,我曾经将主机名添加到主机的 /etc/hosts 并使用--net=host
运行容器。
现在我在 kubernetes 集群中运行我的容器。 我想知道如何通过yaml
将 /etc/hosts 条目添加到 pod 中。
我正在使用 kubernetes v1.5.3。
从 k8s 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"
主机文件会给你带来问题,但如果你真的需要,你可以使用配置映射。
像这样添加一个配置映射
apiVersion: v1
kind: ConfigMap
metadata:
name: my-app-hosts-file-configmap
data:
hosts: |-
192.168.0.1 gateway
127.0.0.1 localhost
然后将其安装在您的 pod 中,如下所示:
volumeMounts:
- name: my-app-hosts-file
mountPath: /etc/
volumes:
- name: my-app-hosts-file
configMap:
name: my-app-hosts-file-configmap
这有效并且看起来更简单:
kind: Service
apiVersion: v1
metadata:
name: {HOST_NAME}
spec:
ports:
- protocol: TCP
port: {PORT}
targetPort: {PORT}
type: ExternalName
externalName: {EXTERNAL_IP}
现在您可以直接使用 pod 中的HOST_NAME
来访问外部机器。
我本人并不需要POD中的主机条目,但是从理论上讲,您应该将这些条目添加到容器的dockerfile
中,而不是作为Pod yaml的一部分-即使可以使用command
参数, 如此答案中所述 。
原因是Pod在逻辑上是一层包裹在容器周围的层,不应与在容器内运行的应用程序的细节有关。
另一种方法是在 pod生命周期上使用postStart钩子,如下所示:
lifecycle: postStart: exec: command: ["/bin/sh", "-c", "echo '192.168.1.10 weblogic-jms1.apizone.io' >> /etc/hosts; echo '192.168.1.20
weblogic-jms2.apizone.io' >> /etc/hosts; echo '192.168.1.30 weblogic-jms3.apizone.io' >> /etc/hosts; echo '192.168.1.40 weblogic-jms4.apizone.io' >> /etc/hosts"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.