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

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

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


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.

Tags:

Kubernetes