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

4/15/2016

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?

-- CESCO
kubernetes

3 Answers

1/10/2019

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

-- Gajus
Source: StackOverflow

4/15/2016

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.

-- Yu-Ju Hong
Source: StackOverflow

3/1/2018

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
-- hammady
Source: StackOverflow