如何将自定义主机条目添加到 kubernetes Pods?
How to add custom host entries to kubernetes Pods?
我的应用程序通过主机名与某些服务通信。
当 运行 将我的应用程序设置为 docker 容器时,我曾使用 --net=host
将主机名添加到主机的 /etc/hosts 和 运行 容器中。
现在我运行在 kubernetes 集群中安装我的容器。我想知道如何通过 yaml
.
将 /etc/hosts 条目添加到广告连播
我正在使用 kubernetes v1.5.3。
主机文件会给你带来问题,但如果你真的需要,你可以使用 configmap。
像这样添加一个 configmap
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
访问外部机器。
从 k8s 1.7 开始,您可以添加 hostAliases
。 Example from the docs:
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"
另一种方法是在 pod lifecycle 上使用 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"]
我的应用程序通过主机名与某些服务通信。
当 运行 将我的应用程序设置为 docker 容器时,我曾使用 --net=host
将主机名添加到主机的 /etc/hosts 和 运行 容器中。
现在我运行在 kubernetes 集群中安装我的容器。我想知道如何通过 yaml
.
我正在使用 kubernetes v1.5.3。
主机文件会给你带来问题,但如果你真的需要,你可以使用 configmap。
像这样添加一个 configmap
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
访问外部机器。
从 k8s 1.7 开始,您可以添加 hostAliases
。 Example from the docs:
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"
另一种方法是在 pod lifecycle 上使用 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"]