Lesson 46 · Section 5: Application Lifecycle Management
Lesson 46: Configure applications: one image, many setups
The map for the rest of this section: why settings stay out of the image, the three ways a value reaches a container (command line, environment variables, files), where those values are stored, and what it takes for a change to reach a running Pod. · 16 min read · 5 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 configuration is kept apart from the image
An image is built once and should run everywhere: on a laptop, in a test cluster, in production. Those places differ in small but important ways. The database has another address, the log level is higher in testing, a feature is switched on for one customer only, the password is different. If any of that is written into the image, you need a separate image for each place, a rebuild for every change, and anyone who can pull the image can read the password.
So the image keeps only the program and its defaults, and everything that varies is handed to the container when it starts. Kubernetes calls that configuring the application, and this section of the course is about the tools for it. This lesson gives you the map; the next lessons cover each tool in depth.
The three doors into a container
Parts:
- ConfigMap (plain settings)
- Secret (passwords, keys)
- Command line (command, args)
- Environment (env, envFrom)
- Files (volumes)
- Container (the same image)
Connections:
- ConfigMap to Environment
- ConfigMap to Files
- Secret to Environment
- Secret to Files
- Command line to Container
- Environment to Container
- Files to Container
A container is an ordinary process. A process can be told things in exactly three ways, and Kubernetes has a field for each:
| Door | Pod field | Good for | Example |
|---|---|---|---|
| Command line | command, args | Choosing what the image runs and with which flags | args: ["--port=8080"] |
| Environment variables | env, envFrom | A handful of simple values | LOG_LEVEL=info |
| Files | volumes, volumeMounts | Whole configuration files, certificates, anything long | /etc/nginx/conf.d/default.conf |
Everything else you will meet in this section ends at one of these doors. That is the most useful thing to hold on to, because it separates two questions that are easy to mix up:
- How does the value reach the process? Through the command line, a variable or a file.
- Where is the value kept? Written directly in the Pod template, in a ConfigMap, or in a Secret.
| Where the value is kept | Use it for | Can arrive as |
|---|---|---|
| The Pod template itself | Values that belong to this one workload | Arguments, variables |
| ConfigMap | Plain settings you want to share or change without touching the workload | Variables, files |
| Secret | Passwords, tokens, keys, certificates | Variables, files |
A ConfigMap and a Secret are used in the same way. The difference is how the cluster treats them: Secret values are
base64-encoded (which is not encryption), are hidden by kubectl describe, can be given tighter RBAC rules, and
are kept in memory, not on disk, on the node. Both are limited to 1 MiB, and both belong to a namespace: a Pod can
only use the ones in its own namespace.
Command line: command and args
An image has a default program (ENTRYPOINT in a Dockerfile) and default arguments (CMD). The Pod template can
replace either one:
| You set | The container runs |
|---|---|
| nothing | The image's ENTRYPOINT with the image's CMD |
args only | The image's ENTRYPOINT with your args |
command only | Your command, and the image's CMD is dropped |
command and args | Your command with your args |
So command replaces ENTRYPOINT and args replaces CMD. The names do not match, which is the usual source of
confusion, and lessons 47 and 48 spend their time on it.
Environment variables: env and envFrom
env sets variables one at a time. Each one has either a value written in place, or a valueFrom that points at
one key of a ConfigMap (configMapKeyRef) or of a Secret (secretKeyRef). envFrom brings in every key of a
ConfigMap or Secret at once, each key becoming a variable of the same name.
When the same name is set more than once, the order is fixed: among envFrom sources the last one wins, and an
entry under env beats anything from envFrom.
Files: volumes
A ConfigMap or Secret can also be a volume. Each key becomes a file named after the key, with the value as its
contents, in the directory where you mount the volume. This is the door for anything that is naturally a file: an
nginx.conf, a TLS certificate, a properties file.
How it works
Parts:
- You (kubectl apply)
- API server (stores the objects)
- kubelet (resolves references)
- ConfigMap, Secret (in the Pod's namespace)
- Container (args, env, files set)
Connections:
- You to API server: Pod
- API server to kubelet: Pod for its node
- ConfigMap, Secret to kubelet: values
- kubelet to Container: starts
The Pod template never contains the values of a ConfigMap or Secret, only their names. Turning names into values is the kubelet's job, and it happens late:
- You apply the Pod (or the Deployment that creates it). The API server validates the shape of the manifest and stores it. It does not check that the ConfigMap or Secret you named exists.
- The scheduler picks a node, and the kubelet on that node sees the Pod.
- Just before it creates each container, the kubelet reads the ConfigMaps and Secrets the container refers to, from
the Pod's own namespace. It builds the final list of environment variables, writes the files for the volumes, and
expands any
$(VAR)references incommand,argsandenvvalues. - The kubelet asks the container runtime to start the container with exactly that command line, environment and set of mounts.
Two things follow from this order, and both come up in the exam.
A wrong reference fails late. kubectl apply succeeds, and the problem appears on the Pod:
| What is wrong | What you see | Where the detail is |
|---|---|---|
env or envFrom names a ConfigMap, Secret or key that does not exist | Pod status CreateContainerConfigError | Events in kubectl describe pod |
| A volume names a ConfigMap or Secret that does not exist | Pod stays in ContainerCreating | A FailedMount event in kubectl describe pod |
| The command or an argument is wrong | The container starts and exits again: Error, then CrashLoopBackOff | kubectl logs, and kubectl describe pod if the program is not in the image |
The kubelet keeps retrying, so creating the missing object is enough: the Pod starts by itself a little later. A
reference can also be marked optional: true, and then the Pod starts without it.
Values are filled in at start. The command line and the environment of a process cannot be changed from outside once it runs. Whatever the kubelet resolved when the container started is what the container keeps.
Parts:
- ConfigMap (edited just now)
- Used as env (keeps the old value)
- subPath mount (keeps the old file)
- Volume mount (file refreshes)
Connections:
- ConfigMap to Used as env: read at start
- ConfigMap to subPath mount: never synced
- ConfigMap to Volume mount: kubelet syncs
That gives the rule for changes:
| You change | What happens to running Pods |
|---|---|
command, args, env or envFrom in a Deployment's Pod template | A rollout starts: new Pods with the new settings replace the old ones |
| The same fields on a bare Pod | Refused. These fields cannot be updated on a Pod; delete it and create it again |
| A ConfigMap or Secret used as environment variables | Nothing. Running containers keep the old values until they are replaced |
| A ConfigMap or Secret mounted as a volume | The kubelet refreshes the files, usually within a minute or so. The application still has to reread them |
A ConfigMap or Secret mounted with subPath | Nothing. A subPath mount is never refreshed |
A Deployment does not watch the ConfigMaps and Secrets its Pods use. Editing one changes nothing in the Deployment,
so no rollout starts. When Pods must pick up the new values, start one yourself with kubectl rollout restart.
Under the hood · How $(VAR) expansion differs from the shell
Inside command, args and the value of an env entry, Kubernetes replaces $(NAME) with the value of the
container's variable NAME. The kubelet does this itself, before the container starts, so it works even in images
that have no shell.
- Round brackets, not curly ones:
$(LOG_LEVEL).$LOG_LEVELand${LOG_LEVEL}are left as they are, and only mean something if the program you start is a shell. - In
env, a variable can only use variables defined above it in the list. - A reference that cannot be resolved is not an error: the text
$(NAME)is passed through unchanged. If you see that literal text in the output of your application, the variable name is wrong. $$(NAME)is the escape, and produces the literal text$(NAME).
env:
- name: LOG_LEVEL
value: "debug"
args: ["--log-level=$(LOG_LEVEL)"]
Under the hood · Immutable ConfigMaps and Secrets
A ConfigMap or Secret can carry the top-level field immutable: true. After that its data cannot be changed, and
the field cannot be removed again: the only way forward is to delete the object and create a new one. It protects
against an accidental edit that would break every Pod reading it, and it saves work in large clusters because the
kubelets stop watching the object.
The common pattern is to put a version in the name (web-settings-v2), create the new object, and point the
Deployment at it. That is a template change, so it rolls out gradually and can be rolled back, which a plain edit
of a ConfigMap cannot.
Using it
Example · See all three doors on one Deployment
The namespace shop holds a ConfigMap web-settings, a ConfigMap web-site with a key default.conf, and a
Secret web-db with a key password. This Deployment uses them through every door:
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
namespace: shop
spec:
replicas: 2
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: nginx
image: nginx:1.29
args: ["nginx-debug", "-g", "daemon off;"] # command line: replaces the image's CMD
env:
- name: LOG_LEVEL # a value written in place
value: "debug"
- name: DB_PASSWORD # one key of a Secret
valueFrom:
secretKeyRef:
name: web-db
key: password
envFrom:
- configMapRef: # every key of a ConfigMap
name: web-settings
volumeMounts:
- name: site
mountPath: /etc/nginx/conf.d # files: one per key of web-site
volumes:
- name: site
configMap:
name: web-site
web-settings also has a key LOG_LEVEL, set to info. The container still sees debug, because env beats
envFrom.
Example · Create the ConfigMaps and the Secret without writing YAML
kubectl -n shop create configmap web-settings \
--from-literal=APP_COLOR=blue --from-literal=LOG_LEVEL=info
kubectl -n shop create configmap web-site --from-file=default.conf # key = file name
kubectl -n shop create secret generic web-db --from-literal=password='S3cure!pass'
--from-literal makes one key per flag. --from-file makes one key per file, named after the file, which is
exactly what you want for a volume. Add --dry-run=client -o yaml to any of them to get the manifest instead.
Example · Configure an existing Deployment from the command line
kubectl set env edits the variables of a workload in place, and every change is a rollout:
kubectl -n shop set env deployment/web LOG_LEVEL=debug # set one variable
kubectl -n shop set env deployment/web --from=configmap/web-settings # one variable per key
kubectl -n shop set env deployment/web --from=secret/web-db --prefix=DB_ # DB_PASSWORD, from the Secret
kubectl -n shop set env deployment/web APP_COLOR- # trailing minus removes it
kubectl -n shop rollout status deployment/web
For a new Pod, kubectl run covers two of the three doors:
kubectl run box --image=busybox:1.37 --env=LOG_LEVEL=debug -- sleep 3600 # after --: args
kubectl run box --image=busybox:1.37 --env=LOG_LEVEL=debug --command -- sleep 3600 # with --command: command
Example · Check what the container really got
Never trust the manifest alone. Ask the running container:
kubectl -n shop set env deployment/web --list # variables as the template defines them
kubectl -n shop exec deploy/web -- env | grep -E 'APP_COLOR|LOG_LEVEL'
kubectl -n shop exec deploy/web -- ls /etc/nginx/conf.d # one file per ConfigMap key
kubectl -n shop exec deploy/web -- cat /etc/nginx/conf.d/default.conf
kubectl -n shop get pod -l app=web -o jsonpath='{.items[0].spec.containers[0].args}'
APP_COLOR=blue
LOG_LEVEL=debug
kubectl exec deploy/web picks one Pod of the Deployment for you, so you do not have to copy a Pod name.
Example · Change a setting and make it arrive
The ConfigMap web-settings is read as environment variables, so an edit alone changes nothing:
kubectl -n shop edit configmap web-settings # APP_COLOR: blue -> green
kubectl -n shop exec deploy/web -- env | grep APP_COLOR # still blue
kubectl -n shop rollout restart deployment/web
kubectl -n shop rollout status deployment/web
kubectl -n shop exec deploy/web -- env | grep APP_COLOR # green
The file from web-site behaves differently. After an edit of that ConfigMap, cat shows the new contents within
a minute or so without any restart. Whether nginx uses them is another matter: nginx reads its configuration at
start, so it still needs a reload or a restart.
Tricks
Common mistakes
- Mixing up
commandandargs.commandreplaces the image'sENTRYPOINT, andargsreplaces itsCMD. Setting onlycommandalso drops the image's default arguments. - Writing a command as one string.
command: ["sleep 3600"]looks for a program calledsleep 3600. Each word is its own item:command: ["sleep", "3600"]. - Expecting a shell.
commandandargsare not run by a shell, so$HOME,|,&&and>do nothing unless you start one yourself:command: ["sh", "-c", "echo $HOME > /tmp/out"]. - Referring to a ConfigMap or Secret in another namespace. There is no field for it. The object must be in the Pod's namespace.
- A typo in a name or key. The manifest applies, and the Pod sits in
CreateContainerConfigErrororContainerCreating.kubectl describe podnames the missing object or key. - Editing a ConfigMap and expecting the Pods to change. Variables are fixed at start, and a Deployment does not notice the edit. Restart the rollout.
- Putting a password in a ConfigMap, or in
envas plain text. It works, and anyone who can read the Pod or the ConfigMap can read the password. Use a Secret and asecretKeyRef. - Treating base64 as protection.
kubectl get secret web-db -o jsonpath='{.data.password}' | base64 -dprints the password. What protects a Secret is RBAC, and encryption at rest (lesson 52).
Recap
- The image holds the program and its defaults. Everything that varies comes from outside, so one image serves every environment.
- There are three doors into a container: the command line (
command,args), environment variables (env,envFrom) and files (volumes). - Values are kept in the Pod template, in a ConfigMap (plain settings) or in a Secret (sensitive ones). Both can arrive as variables or as files.
- The kubelet resolves the references when it creates the container. A wrong name fails there, as
CreateContainerConfigErroror a Pod stuck inContainerCreating. - A template change rolls out by itself. An edited ConfigMap or Secret does not: only plain volume mounts refresh,
and for everything else you run
kubectl rollout restart. - Next: commands and arguments in Docker and in Kubernetes, then environment variables, ConfigMaps and Secrets, each in its own lesson.
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.
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.