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
Official competencies this lesson covers
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:
envbelongs to a container, not to the Pod. It sits at the same level asimage. A Pod with two containers has two separateenvlists, and a variable set on one is invisible to the other. Init containers have their own list too.envis a list. Each item starts with a dash and has anameand either avalueor avalueFrom.- A value is always a string.
value: 4andvalue: trueare rejected, because YAML reads them as a number and a boolean. Writevalue: "4"andvalue: "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
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 write | The value is | Typical use |
|---|---|---|
value: "debug" | The literal text | Settings that belong to this workload only |
valueFrom.configMapKeyRef | One key of a ConfigMap | Settings shared by several workloads |
valueFrom.secretKeyRef | One key of a Secret | Passwords, tokens |
valueFrom.fieldRef | A field of the Pod itself | The Pod's name, namespace, IP, node |
valueFrom.resourceFieldRef | A CPU or memory request or limit of a container | Sizing 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.
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:
envof an existing Pod cannot be edited.kubectl edit podandkubectl set env pod/…are refused withForbidden: 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, usekubectl 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/NAMEto get Pods that read the new value.
Which value wins
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:
ENVlines of the image.- Variables the kubelet adds for Services (see below).
envFromsources, in the order they are listed. If two sources share a key, the later source wins.- The
envlist. 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, inenvvalues,commandandargs. No shell is involved.$VARand${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. Withcommand: ["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
PATHandNGINX_VERSIONcome from the image.HOSTNAMEis 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_HOSTandNAME_SERVICE_PORT(the Service name in upper case, dashes turned into underscores), plus a fewNAME_PORT…variables in an older Docker format. ThekubernetesService of thedefaultnamespace 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
fieldPath | Gives |
|---|---|
metadata.name, metadata.namespace, metadata.uid | The Pod's name, namespace and unique ID |
metadata.labels['app'], metadata.annotations['team'] | One label or annotation |
spec.nodeName, spec.serviceAccountName | The node and the service account |
status.podIP, status.hostIP | The 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 variable | Mounted file | |
|---|---|---|
| When it is read | Once, at container start | Whenever the application opens the file |
| After the ConfigMap changes | Old value until the Pod is replaced | The file is updated within about a minute |
| Good for | Short single values | Whole configuration files, certificates |
| Exposure | Visible to anything that can run env or read /proc, and often dumped into crash reports | Limited 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
- Generate or edit
- Quote the values
- Apply
- exec env to verify
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: 8080orvalue: truefails withcannot unmarshal number(orbool)… of type string. Quote it. envat the wrong level. Underspecinstead of under the container, the API server answersunknown field "spec.env". In a Deployment it belongs atspec.template.spec.containers[].env.- Trying to change a running Pod.
envis 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 ofenv. $VARwithout a shell. Kubernetes expands$(VAR);$VARneedssh -c.- Mixing up the two reference shapes. Under
envit isvalueFrom.configMapKeyRefwithnameandkey. UnderenvFromit isconfigMapRefwith onlyname.secretKeyRefandsecretReffollow 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 execpicks the first one. Add-c NAME.
Recap
- Variables are set per container in the
envlist; each has anameand a stringvalue, or avalueFromreference to a ConfigMap key, a Secret key or a field of the Pod.envFromimports 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 restartafter editing a ConfigMap. - Order of precedence: image, Service variables,
envFrom(later sources win), thenenv, which beats them all. $(NAME)reuses a variable defined earlier in the list, and also works incommandandargs.- Fast path:
kubectl run … --env,kubectl set env deployment/NAME KEY=value(andKEY-to remove), then prove it withkubectl 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.