How to access container environment variables with kubernetes env?

10/16/2020

I'm trying to run my application on Kubernetes. My docker container have environment variables such as PATH and LD_LIBRARY_PATH, which are set in Dockerfile. I tried to change them in the yaml file like this:

env:
- name: LD_LIBRARY_PATH
  value: "foo:$(LD_LIBRARY_PATH)"

The above configuration doesn't work, I just see LD_LIBRARY_PATH=foo:$(LD_LIBRARY_PATH) in the pod. This method seems work for Kubernetes env variables such as KUBERNETES_PORT_443_TCP_PROTO, but not for docker env variables.

My questions are:

  1. I think the env settings in yaml are injected into docker before the running time of the container, so kubernetes cannot read the value of LD_LIBRARY_PATH. Therefor it can't change the variable. Do I understand it right?

  2. How to change container environment variables with kubernetes env? I know that I can set the env variables in the command field of yaml file, but that seems not clean and are there other ways to do that?

  3. If Kubernetes can't change existed envs, does it mean that the env field in yaml file is designed to add new envs only?

Thank you!

-- Rui
docker
environment-variables
kubernetes

1 Answer

10/16/2020

The Kubernetes variable expansion syntax only works on things Kubernetes directly knows about. Inside a container an environment variable could come from a couple of places (the Dockerfile ENV directive, the base container environment itself, setup in an entrypoint script) and Kubernetes doesn't consider any of these; it only considers things in the same container spec. The API definition of EnvVar hints at this:

Variable references $(VAR_NAME) are expanded using the previous defined environment variables in the container and any service environment variables.

You can't use this Kubernetes syntax to change environment variables in the way you're describing. You can only refer to other things in the same env: block (which may come from ConfigMaps or Secrets) and the implicit variables that come from other Services.

(Changing path-type variables at the Kubernetes level doesn't make a lot of sense. Since an image is self-contained, it already contains all of the commands and libraries it would need. It's difficult in Kubernetes to inject more tools or libraries; it'd be better to install them directly in your image, ideally in /usr/lib or /usr/local/lib, but failing that you can update ENV in a Dockerfile similar to how you suggest here.)

-- David Maze
Source: StackOverflow