How do I tell if my container is running inside a Kubernetes cluster?

前端 未结 3 1341
慢半拍i
慢半拍i 2021-01-17 09:33

How can I tell whether or not I am running inside a kubernetes cluster? With docker I can check if /.dockerinit exist. Is there an equivalent?

相关标签:
3条回答
  • 2021-01-17 10:01

    You can pass environment variables to your containers in the pod spec. You can even expose some pod information to the containers via environment variables using the downward API.

    0 讨论(0)
  • 2021-01-17 10:05

    With the default configuration, Kubernetes will mount the serviceaccount secrets into pods. Simply check for the existence of this folder: /var/run/secrets/kubernetes.io. No need to set environment variables. In ruby I would do the following:

    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
    
    0 讨论(0)
  • 2021-01-17 10:12

    You can check for KUBERNETES_SERVICE_HOST environment variable.

    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

    0 讨论(0)
提交回复
热议问题