Kubernetes environment variables

In Cloud Consulting


In this article we will look at what resources and environment variables are available to containers and how to override environment variables for a container when running a Pod in a Kubernetes cluster
alt
Editorial Commitee Qualified.One,
Management
alt

Let's get this straight!

There are several important resources available to a running container in Kubernetes

  • the filesystem, which is a combination of a docker image (layers) and one or more volumes;
  • information about the container itself;
  • information about the other objects in the cluster.

Information about the container itself usually includes:

  • Hostname, which is the name of the Pod in which the container runs. It can be accessed through the hostname command or by calling the gethostname function;
  • Pod namespace - available as environment variables;
  • Custom environment variables from the Pod manifest (description) - we will talk about them later;
  • Environment variables set statically in the docker image (e.g., at build time).

Information about other objects in the Kubernetes cluster is also available to the container as environment variables. For example, a service named foo, inside a container named bar will appear in the environment variables as follows:


FOO_SERVICE_HOST=
FOO_SERVICE_PORT=

When creating a Pod, you can set environment variables for the containers that are running in that Pod. To do this, add to configuration file (manifest) field env or envFrom, for example:


apiVersion: v1
kind: Pod
metadata:
  name: envar-demo
  labels:
    purpose: demonstrate-envars
spec:
  containers:
  - name: envar-demo-container
    image: gcr.io/google-samples/node-hello:1.0
    env:
    - name: DEMO_GREETING
      value: "Hello from the environment"
    - name: DEMO_FAREWELL
      value: "Such a sweet sorrow"

Save the suggested manifest in the envars.yaml file and run the pod in a Kubernetes cluster:


kubectl create -f envars.yaml

Check the list of running pods:


kubectl get pods -l purpose=demonstrate-envars

The result of the previous command will be something like this:


NAME            READY     STATUS    RESTARTS   AGE
 envar-demo      1/1       Running   0          9s

Connect to the running container:


kubectl exec -it envar-demo -- /bin/bash

Display the environment variables with printenv (the output is shortened):


root@envar-demo:/# printenv

NODE_VERSION=4.4.2
EXAMPLE_SERVICE_PORT_8080_TCP_ADDR=10.3.245.237
HOSTNAME=envar-demo
...
DEMO_GREETING=Hello from the environment
DEMO_FAREWELL=Such a sweet sorrow

Note. It is worth remembering that variables set with env or envFrom override the values of variables set in the docker image.