Skip to content
LF Cert Trainer

Lesson 49 · Section 5: Application Lifecycle Management

Lesson 49: Configure environment variables in applications

How a container gets its environment variables: literal values, values pulled from ConfigMaps, Secrets and the Pod itself, which value wins when a name is set twice, why a running container never sees a change, and the kubectl commands that set and check them in seconds. · 20 min read · 4 min video

1/11Environment variables
0:00 / 3:52

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Why applications read their settings from the environment

An image is built once and should run everywhere: on your laptop, in a test cluster, in production. What differs between those places is configuration: the address of the database, the log level, the name of the region, a feature switch. If those values were baked into the image, every change would mean a new build and a new rollout of a different image.

The oldest and simplest way out is the environment variable: a named string that the operating system hands to a process when it starts. Almost every language reads them with one line (os.environ["DB_HOST"], process.env.DB_HOST, System.getenv("DB_HOST")), and almost every public image is configured through them (POSTGRES_PASSWORD, MYSQL_DATABASE, NGINX_PORT). With Docker you pass them with docker run -e DB_HOST=db. In Kubernetes you declare them in the Pod spec, next to the container that needs them.

What it is: the env list of a container

apiVersion: v1
kind: Pod
metadata:
  name: api
spec:
  containers:
    - name: api
      image: nginx:1.29
      env:
        - name: LOG_LEVEL
          value: debug
        - name: WORKERS
          value: "4"
        - name: DB_HOST
          value: db.shop.svc

Three things to notice:

  • env belongs to a container, not to the Pod. It sits at the same level as image. A Pod with two containers has two separate env lists, and a variable set on one is invisible to the other. Init containers have their own list too.
  • env is a list. Each item starts with a dash and has a name and either a value or a valueFrom.
  • A value is always a string. value: 4 and value: true are rejected, because YAML reads them as a number and a boolean. Write value: "4" and value: "true".

The name is conventionally upper case with underscores (DB_HOST). The convention is not a rule for Kubernetes: recent versions accept almost any printable character except =. It is a rule for many shells and programs, though, so a name like db-host is stored happily and then cannot be read with $db-host in a script. Stay with letters, digits and underscores, and do not start with a digit.

Where a value can come from

Where a container's environment variables come fromenvLiteral valuevalue: "debug"ConfigMap, SecretvalueFrom, envFromThe Pod itselffieldRef: podIPServicesWEB_SERVICE_HOSTkubeletresolves at startContainer processreads plain strings
Where a container's environment variables come from. The Pod spec only says where each value lives. The kubelet looks every value up once, when it starts the container, and hands the process a plain list of strings.

Parts:

  • Literal value (value: "debug")
  • ConfigMap, Secret (valueFrom, envFrom)
  • The Pod itself (fieldRef: podIP)
  • Services (WEB_SERVICE_HOST)
  • kubelet (resolves at start)
  • Container process (reads plain strings)

Connections:

  • Literal value to kubelet
  • ConfigMap, Secret to kubelet
  • The Pod itself to kubelet
  • Services to kubelet
  • kubelet to Container process: env

A value does not have to be typed into the manifest. Each item of the list uses exactly one of these:

You writeThe value isTypical use
value: "debug"The literal textSettings that belong to this workload only
valueFrom.configMapKeyRefOne key of a ConfigMapSettings shared by several workloads
valueFrom.secretKeyRefOne key of a SecretPasswords, tokens
valueFrom.fieldRefA field of the Pod itselfThe Pod's name, namespace, IP, node
valueFrom.resourceFieldRefA CPU or memory request or limit of a containerSizing a thread pool or a heap to the limit

And next to env, a second field, envFrom, imports every key of a ConfigMap or Secret as a variable in one go. ConfigMaps and Secrets each get their own lesson next; here you only need to recognise the shapes:

      env:
        - name: DB_HOST                 # one key, and you choose the variable's name
          valueFrom:
            configMapKeyRef:
              name: app-config
              key: db_host
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: db-credentials
              key: password
      envFrom:                          # every key, and the key is the variable's name
        - configMapRef:
            name: app-config

How it works

The kubelet resolves everything once, at start

Nothing in the cluster "pushes" variables into a container. When the kubelet is about to start a container, it builds the complete environment for it: it copies the literal values, reads the referenced ConfigMaps and Secrets through the API server, fills in the Pod's own fields, and passes the finished list of NAME=value strings to the container runtime. The runtime starts the process with that environment, on top of whatever the image defined with ENV.

From then on the environment is ordinary process memory. Kubernetes has no way to reach into a running process and change it, and neither does Linux.

The environment is a copy made at startcopystartreplaced byPod templateLOG_LEVEL: infokubeletstarts containerRunning containerLOG_LEVEL=infoYou change itkubectl set envDeploymentrolls out new PodsNew containerLOG_LEVEL=debug
The environment is a copy made at start. A running process keeps the environment it was started with. A new value reaches the application only through a new container, which a Deployment creates for you when its Pod template changes.

Parts:

  • Pod template (LOG_LEVEL: info)
  • kubelet (starts container)
  • Running container (LOG_LEVEL=info)
  • You change it (kubectl set env)
  • Deployment (rolls out new Pods)
  • New container (LOG_LEVEL=debug)

Connections:

  • Pod template to kubelet
  • kubelet to Running container: copy
  • You change it to Deployment
  • Deployment to New container: start
  • Running container to New container: replaced by

Two consequences that people trip over:

  • env of an existing Pod cannot be edited. kubectl edit pod and kubectl set env pod/… are refused with Forbidden: pod updates may not change fields other than …. Change the Pod template of the Deployment instead, and the Deployment replaces the Pods with a rolling update. For a bare Pod, use kubectl replace --force -f.
  • Editing a ConfigMap or a Secret does not change the variables of running containers. The reference was resolved when the container started. The template of the Deployment did not change either, so nothing rolls out by itself. Run kubectl rollout restart deployment/NAME to get Pods that read the new value.

Which value wins

Which value wins when a name is set more than onceImageENV in DockerfileService variablesadded by kubeletenvFromwhole ConfigMapsenvnamed one by oneContainer seeslast writer wins
Which value wins when a name is set more than once. The environment is built in layers, and each layer overrides the one before it. A variable you name in env always beats the same name from envFrom, from a Service or from the image.

Parts:

  • Image (ENV in Dockerfile)
  • Service variables (added by kubelet)
  • envFrom (whole ConfigMaps)
  • env (named one by one)
  • Container sees (last writer wins)

Connections:

  • Image to Service variables
  • Service variables to envFrom
  • envFrom to env
  • env to Container sees

The same name can arrive from several places, and the kubelet applies them in a fixed order. Later layers override earlier ones:

  1. ENV lines of the image.
  2. Variables the kubelet adds for Services (see below).
  3. envFrom sources, in the order they are listed. If two sources share a key, the later source wins.
  4. The env list. A name set here beats the same name from everything above.

So env is how you override a single key of a ConfigMap that you import as a whole with envFrom.

Variables that depend on other variables

A value can contain $(NAME), with round brackets, and Kubernetes replaces it with the value of that variable:

      env:
        - name: DB_HOST
          value: db.shop.svc
        - name: DB_URL
          value: "postgres://$(DB_HOST):5432/shop"   # postgres://db.shop.svc:5432/shop
        - name: BROKEN_URL
          value: "http://$(API_HOST)/v1"             # stays http://$(API_HOST)/v1
        - name: API_HOST
          value: api.shop.svc

Order matters. Only variables defined above in the list (and the Service variables) can be used. BROKEN_URL refers to API_HOST before it exists, so the text is left exactly as written. That is not an error: the container starts, and the application receives a literal $(API_HOST). To keep the characters on purpose, double the dollar sign: $$(API_HOST).

The same $(NAME) syntax works in the container's command and args, which is how you hand a variable to a program as a flag without starting a shell:

      command: ["my-server"]
      args: ["--log-level=$(LOG_LEVEL)"]
Under the hood · $(VAR), $VAR and who expands what

There are two different mechanisms that look alike.

  • $(VAR) is expanded by Kubernetes, before the process starts, in env values, command and args. No shell is involved.
  • $VAR and ${VAR} are expanded by a shell, inside the container, and only if a shell actually runs your command. args: ["echo $LOG_LEVEL"] given to a program that is not a shell prints the text $LOG_LEVEL. With command: ["sh", "-c"] in front, the shell replaces it.

When a variable seems "not set", first check which of the two you wrote and whether anything is there to expand it.

Variables the Pod did not ask for

Run env in any container and you see more than you declared:

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=api
NGINX_VERSION=1.29.3
KUBERNETES_SERVICE_HOST=10.96.0.1
KUBERNETES_SERVICE_PORT=443
WEB_SERVICE_HOST=10.96.44.17
WEB_SERVICE_PORT=80
WEB_PORT=tcp://10.96.44.17:80
LOG_LEVEL=debug
  • PATH and NGINX_VERSION come from the image. HOSTNAME is set by the runtime to the Pod's name.
  • For every Service that exists in the Pod's namespace when the container starts, the kubelet adds NAME_SERVICE_HOST and NAME_SERVICE_PORT (the Service name in upper case, dashes turned into underscores), plus a few NAME_PORT… variables in an older Docker format. The kubernetes Service of the default namespace is always included, which is how in-cluster clients find the API server.

This was the service discovery of early Kubernetes, before cluster DNS. It only knows Services that existed before the Pod started, so use DNS names instead. If the extra variables get in the way, switch them off for a Pod with spec.enableServiceLinks: false (the KUBERNETES_… ones stay).

The Pod describing itself

A container often needs to know facts that exist only once the Pod runs: its own name for log lines, its IP to announce itself to peers, the node it landed on. fieldRef copies them in, an approach called the downward API:

      env:
        - name: POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        - name: MEMORY_LIMIT_MI
          valueFrom:
            resourceFieldRef:
              resource: limits.memory
              divisor: 1Mi
fieldPathGives
metadata.name, metadata.namespace, metadata.uidThe Pod's name, namespace and unique ID
metadata.labels['app'], metadata.annotations['team']One label or annotation
spec.nodeName, spec.serviceAccountNameThe node and the service account
status.podIP, status.hostIPThe Pod's IP and the node's IP

resourceFieldRef reads requests.cpu, limits.cpu, requests.memory or limits.memory of a container, and divisor chooses the unit (1Mi gives mebibytes, 1m gives millicores).

Under the hood · Environment variables or mounted files?

A ConfigMap or Secret can also be mounted as a volume, where each key becomes a file. The two ways behave differently:

Environment variableMounted file
When it is readOnce, at container startWhenever the application opens the file
After the ConfigMap changesOld value until the Pod is replacedThe file is updated within about a minute
Good forShort single valuesWhole configuration files, certificates
ExposureVisible to anything that can run env or read /proc, and often dumped into crash reportsLimited by file permissions

That last row is why security guides prefer files for Secrets. For the exam, do what the task says: "as an environment variable" means env or envFrom.

Newer clusters know one more source, valueFrom.fileKeyRef, which reads a KEY=value file that an init container wrote into an emptyDir volume. It is still behind a feature gate on many clusters, so do not count on it.

Using it

  1. Generate or edit
  2. Quote the values
  3. Apply
  4. exec env to verify
The routine for every variable task

Example · A new Pod with two variables

Create a Pod named api in namespace shop that runs nginx:1.29 with LOG_LEVEL=debug and WORKERS=4.

Every requirement has a flag, so one command is enough. --env can be repeated:

kubectl run api -n shop --image=nginx:1.29 --env=LOG_LEVEL=debug --env=WORKERS=4

If the task asks for a file, or you need to add more afterwards, generate the manifest instead:

kubectl run api -n shop --image=nginx:1.29 --env=LOG_LEVEL=debug --env=WORKERS=4 \
  --dry-run=client -o yaml > api.yaml

kubectl writes the list for you, with the quotes in the right place:

    env:
    - name: LOG_LEVEL
      value: debug
    - name: WORKERS
      value: "4"

Verify from inside the container, not from the manifest:

kubectl exec api -n shop -- env | grep -E 'LOG_LEVEL|WORKERS'
# LOG_LEVEL=debug
# WORKERS=4

Example · Change a variable on a running Deployment

The Deployment web in namespace shop must run with LOG_LEVEL=warn, and the variable DEBUG must be removed.

kubectl set env edits the Pod template. A trailing minus sign removes a variable:

kubectl set env deployment/web -n shop LOG_LEVEL=warn DEBUG-
# deployment.apps/web env updated

The template changed, so the Deployment starts a rolling update. Wait for it, then check both the configuration and a running container:

kubectl rollout status deployment/web -n shop
kubectl set env deployment/web -n shop --list
# # Deployment web, container nginx
# LOG_LEVEL=warn
kubectl exec -n shop deploy/web -- env | grep -E 'LOG_LEVEL|DEBUG'
# LOG_LEVEL=warn

With several containers in the template, set env changes all of them unless you name one with -c: kubectl set env deployment/web -c nginx LOG_LEVEL=warn.

Example · Mix literal values, references and the Pod's own data

The worker Pod needs QUEUE=orders, the database host from key db_host of ConfigMap app-config, the password from key password of Secret db-credentials, its own Pod name, and a DB_URL built from the host.

Generate the skeleton with the one literal value, then add the references by hand:

kubectl run worker --image=busybox:1.37 --env=QUEUE=orders \
  --dry-run=client -o yaml --command -- sleep 3600 > worker.yaml
    env:
    - name: QUEUE
      value: orders
    - name: DB_HOST
      valueFrom:
        configMapKeyRef:
          name: app-config
          key: db_host
    - name: DB_PASSWORD
      valueFrom:
        secretKeyRef:
          name: db-credentials
          key: password
    - name: POD_NAME
      valueFrom:
        fieldRef:
          fieldPath: metadata.name
    - name: DB_URL
      value: "postgres://$(DB_HOST):5432/$(QUEUE)"

DB_URL is last on purpose: it may only use what is defined above it. Apply and read the result:

kubectl apply -f worker.yaml
kubectl exec worker -- env | grep -E 'QUEUE|DB_|POD_NAME'
# QUEUE=orders
# DB_HOST=db.shop.svc
# DB_PASSWORD=s3cr3t
# POD_NAME=worker
# DB_URL=postgres://db.shop.svc:5432/orders

kubectl describe pod worker shows the same list without resolving it, which is the fastest way to see where each value comes from:

    Environment:
      QUEUE:        orders
      DB_HOST:      <set to the key 'db_host' of config map 'app-config'>  Optional: false
      DB_PASSWORD:  <set to the key 'password' in secret 'db-credentials'>  Optional: false
      POD_NAME:     worker (v1:metadata.name)
      DB_URL:       postgres://$(DB_HOST):5432/$(QUEUE)

Example · A Pod stuck in CreateContainerConfigError

A Pod is accepted, gets a node, and then never starts:

kubectl get pod worker
# NAME     READY   STATUS                       RESTARTS   AGE
# worker   0/1     CreateContainerConfigError   0          40s

This status means the kubelet could not build the container's configuration, and with environment variables the reason is nearly always a reference that points at nothing. The event says which one:

kubectl describe pod worker | tail -n 3
# Warning  Failed  kubelet  Error: configmap "app-config" not found
# or:      Error: couldn't find key db_host in ConfigMap shop/app-config
# or:      Error: secret "db-credentials" not found

Create the missing object, or fix the name or the key in the manifest. The kubelet retries by itself: once the reference resolves, the container starts without you recreating the Pod. Remember that a reference only looks in the Pod's own namespace.

Tricks

Common mistakes

  • An unquoted number or boolean. value: 8080 or value: true fails with cannot unmarshal number (or bool) … of type string. Quote it.
  • env at the wrong level. Under spec instead of under the container, the API server answers unknown field "spec.env". In a Deployment it belongs at spec.template.spec.containers[].env.
  • Trying to change a running Pod. env is immutable on a Pod. Change the Deployment, or replace the bare Pod.
  • Expecting a ConfigMap edit to reach running containers. It reaches mounted files, never variables. Restart the rollout.
  • A dependent variable above the one it uses. $(NAME) only sees earlier items, and a miss leaves the text untouched without any error. Look for a literal $( in the output of env.
  • $VAR without a shell. Kubernetes expands $(VAR); $VAR needs sh -c.
  • Mixing up the two reference shapes. Under env it is valueFrom.configMapKeyRef with name and key. Under envFrom it is configMapRef with only name. secretKeyRef and secretRef follow the same pattern.
  • The same name twice in one list. It is accepted, the last one wins, and kubectl only prints a warning that the earlier definition is hidden.
  • Checking the wrong container. In a Pod with several containers, kubectl exec picks the first one. Add -c NAME.

Recap

  • Variables are set per container in the env list; each has a name and a string value, or a valueFrom reference to a ConfigMap key, a Secret key or a field of the Pod. envFrom imports all keys at once.
  • The kubelet resolves everything once, when the container starts. To change a variable, change the Pod template and let the Deployment roll out, or run kubectl rollout restart after editing a ConfigMap.
  • Order of precedence: image, Service variables, envFrom (later sources win), then env, which beats them all.
  • $(NAME) reuses a variable defined earlier in the list, and also works in command and args.
  • Fast path: kubectl run … --env, kubectl set env deployment/NAME KEY=value (and KEY- to remove), then prove it with kubectl exec POD -- env.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

2 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Give an app its settings as environment variables from a literal, a ConfigMap and a Secret, without copying a value.

    Build · Level 2 · standard · target 15 min

  • Section capstone. One Deployment, five jobs: get it past a broken init container, feed it from a ConfigMap and a Secret, add probes, release a new version with no gap, and prepare it for autoscaling.

    Fix · Level 3 · challenge · target 30 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.