[英]How do I tell if my container is running inside a Kubernetes cluster?
How can I tell whether or not I am running inside a kube.netes cluster?如何判断我是否在 kube.netes 集群中运行? With docker I can check if
/.dockerinit
exist.使用 docker 我可以检查
/.dockerinit
是否存在。 Is there an equivalent?有等价物吗?
You can check for KUBERNETES_SERVICE_HOST
environment variable. 您可以检查
KUBERNETES_SERVICE_HOST
环境变量。
This variable is always exported in an environment where the container is executed. 始终在执行容器的环境中导出此变量。
Refer to https://kubernetes.io/docs/concepts/services-networking/connect-applications-service/#environment-variables 请参阅https://kubernetes.io/docs/concepts/services-networking/connect-applications-service/#environment-variables
You can pass environment variables to your containers in the pod spec. 您可以在pod规范中将环境变量传递给容器。 You can even expose some pod information to the containers via environment variables using the downward API .
您甚至可以使用向下API通过环境变量向容器公开一些pod信息。
With the default configuration, Kubernetes will mount the serviceaccount secrets into pods. 使用默认配置,Kubernetes会将serviceaccount机密挂载到pod中。 Simply check for the existence of this folder:
/var/run/secrets/kubernetes.io
. 只需检查此文件夹是否存在:
/var/run/secrets/kubernetes.io
。 No need to set environment variables. 无需设置环境变量。 In ruby I would do the following:
在ruby中我会做以下事情:
if File.exists?('/.dockerenv')
puts "I'm running in a docker container"
end
if File.exists?('/var/run/secrets/kubernetes.io')
puts "I'm also running in a Kubernetes pod"
end
One option is to check the /etc/hosts
file - there is by default the comment that the file is maintained by K8s.一种选择是检查
/etc/hosts
文件——默认情况下,该文件由 K8s 维护。
Anyway the best way is to def your own env variable in deployment, so use some template tools like helm to gen deployment and define some general template.无论如何,最好的方法是在部署中定义自己的 env 变量,因此使用一些模板工具,如 helm 来生成部署并定义一些通用模板。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.