Skip to content
LF Cert Trainer

Lesson 50 · Section 5: Application Lifecycle Management

Lesson 50: ConfigMaps: configuration that lives outside the image

What a ConfigMap is, the three ways a container receives it (one variable, all variables, files in a volume), how the kubelet delivers it, why some changes arrive live and others need a restart, and the commands that make it quick in the exam. · 22 min read · 4 min video

Official competency this lesson covers

1/11ConfigMaps
0:00 / 4:15

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

Why ConfigMaps exist

Every application has settings that differ from place to place: the mode it runs in, the address of its database, its log level, a whole nginx.conf. There are three places you could put them, and two of them hurt:

  • In the image. Then changing a log level means a new build, and dev and production run different images, so what you tested is not what you ship.
  • In the Pod template. Writing env: value: into each Deployment works (the previous lesson did exactly that), but the same database address ends up copied into ten manifests, and a whole configuration file does not fit in an environment variable comfortably.
  • In an object of its own. One place that holds the settings, that many Pods can point to, and that you can change without touching an image or a Pod template.

That third place is the ConfigMap.

A ConfigMap is for settings that are not secret. Its values are stored and shown in plain text, and anyone who may read ConfigMaps in the namespace can read them. Passwords, tokens and keys go in a Secret, which is the next lesson; everything you learn here about injecting values works the same way there.

What a ConfigMap is

apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
  namespace: shop
data:
  APP_MODE: production          # a short value
  LOG_LEVEL: info
  app.properties: |             # a whole file, under a key that looks like a file name
    cache.size=200
    cache.ttl=30s

There is no spec and no status: a ConfigMap describes nothing that a controller has to make true. It is data, and nothing happens until a Pod refers to it.

FieldWhat it holds
dataKeys with UTF-8 text values. This is what you use almost always
binaryDataKeys with base64-encoded bytes, for content that is not text (a keystore, a small image). kubectl create configmap --from-file fills it in for you when the file is not valid UTF-8
immutabletrue freezes the contents for good. See "Immutable ConfigMaps" below

The rules that are worth knowing by heart:

  • Keys may contain letters, digits, -, _ and ., nothing else. A key is unique across data and binaryData.
  • Values in data are always strings. replicas: 3 or debug: true is rejected; write "3" and "true".
  • The whole object is limited to 1 MiB. A ConfigMap is for configuration, not for data files.
  • It is namespaced, and a Pod can only use ConfigMaps from its own namespace. The short name is cm.

Three ways into a container

Three ways from a ConfigMap into a containerone keyall keysas filesOne variableenv + configMapKeyRefConfigMapapp-configAll variablesenvFromContaineryour applicationFilesconfigMap volume
Three ways from a ConfigMap into a container. One ConfigMap can feed a container as a single environment variable, as one variable per key, or as files in a mounted volume. Variables are read once when the container starts; files are kept up to date.

Parts:

  • One variable (env + configMapKeyRef)
  • ConfigMap (app-config)
  • All variables (envFrom)
  • Container (your application)
  • Files (configMap volume)

Connections:

  • ConfigMap to One variable: one key
  • ConfigMap to All variables: all keys
  • ConfigMap to Files: as files
  • One variable to Container
  • All variables to Container
  • Files to Container

A Pod can consume a ConfigMap in three ways, and one Pod may mix them freely.

WayPod fieldWhat the container seesFollows later changes?
One key as one variableenv[].valueFrom.configMapKeyRefA variable with the name you chooseNo
Every key as a variableenvFrom[].configMapRefOne variable per key, named after the key (plus an optional prefix)No
Keys as filesvolumes[].configMap + volumeMountsA directory with one read-only file per keyYes, after a short delay

(A fourth way exists: the application calls the Kubernetes API and reads the ConfigMap itself. Operators and controllers do that; ordinary applications should not need to know they run on Kubernetes.)

One key, one variable. Use it when the application expects a variable name that differs from the key, or when you want only one or two values out of a larger ConfigMap:

env:
  - name: MODE                       # the name the application reads
    valueFrom:
      configMapKeyRef:
        name: app-config             # the ConfigMap
        key: APP_MODE                # the key inside it

Every key at once. The shortest form, and the one to reach for when the ConfigMap was built for this application:

envFrom:
  - configMapRef:
      name: app-config
    prefix: CFG_                     # optional: APP_MODE arrives as CFG_APP_MODE

Files in a volume. The natural choice for a real configuration file, and the only way that follows changes:

spec:
  containers:
    - name: web
      image: nginx:1.29
      volumeMounts:
        - name: config               # must match the volume's name below
          mountPath: /etc/app        # every key becomes a file in this directory
  volumes:
    - name: config
      configMap:
        name: app-config

With the ConfigMap above, the container finds /etc/app/APP_MODE, /etc/app/LOG_LEVEL and /etc/app/app.properties. The file's name is the key and its content is the value.

When the same variable name comes from more than one place, the order is fixed: among several envFrom sources the last one wins, and anything in env overrides envFrom. That makes a neat pattern: load defaults with envFrom, then override one value for this Deployment with env.

How it works underneath

Who delivers the configurationcreatestoreswatchsets oncerewriteskubectlcreate configmapAPI servervalidates, servesetcdstores the objectkubeleton the Pod's nodeEnvironmentset once at startContainerreads bothVolume filesrefreshed
Who delivers the configuration. The ConfigMap is only data in etcd. The kubelet on the Pod's node fetches it, sets the variables once when it creates the container, and writes the files into a volume that it keeps refreshing.

Parts:

  • kubectl (create configmap)
  • API server (validates, serves)
  • etcd (stores the object)
  • kubelet (on the Pod's node)
  • Environment (set once at start)
  • Container (reads both)
  • Volume files (refreshed)

Connections:

  • kubectl to API server: create
  • API server to etcd: stores
  • API server to kubelet: watch
  • kubelet to Environment: sets once
  • kubelet to Volume files: rewrites
  • Environment to Container
  • Volume files to Container

The API server only stores the ConfigMap. All of the delivery is done by the kubelet on the node where the Pod runs:

  1. The Pod is scheduled to a node. Its kubelet sees which ConfigMaps the Pod refers to and starts watching exactly those objects (not every ConfigMap in the cluster).
  2. For variables, the kubelet resolves every configMapKeyRef and envFrom into plain NAME=value pairs and passes them to the container runtime when it creates the container. From then on they are part of the process's environment, and nothing outside the process can change a process's environment. That is a property of Linux, not a Kubernetes limitation.
  3. For volumes, the kubelet creates a directory on the node, writes one file per key into it and mounts it into the container. It checks on every sync whether the ConfigMap has changed and rewrites the files when it has.

If a ConfigMap or a key that the Pod needs does not exist, the kubelet cannot build the container, and it says so in the Pod's status:

What is missingWhat you seeThe event
ConfigMap named in env or envFromCreateContainerConfigErrorconfigmap "app-config" not found
Key named in configMapKeyRefCreateContainerConfigErrorcouldn't find key APP_MODE in ConfigMap shop/app-config
ConfigMap named in a volumePod stays ContainerCreatingFailedMount ... configmap "app-config" not found

The kubelet keeps retrying. Create the missing ConfigMap and the Pod starts by itself a little later; you do not have to delete it. If the configuration really is optional, say so with optional: true on the reference, and the Pod starts without it.

Under the hood · How the files change without the application seeing half a file

Look inside a mounted ConfigMap with ls -la and you will see more than your keys:

drwxrwxrwx  ..2026_11_30_11_42_07.1873424125/
lrwxrwxrwx  ..data -> ..2026_11_30_11_42_07.1873424125
lrwxrwxrwx  APP_MODE -> ..data/APP_MODE
lrwxrwxrwx  app.properties -> ..data/app.properties

The real files sit in a timestamped directory. ..data is a symbolic link to that directory, and each key is a symbolic link that goes through ..data.

When the ConfigMap changes, the kubelet writes all the new files into a new timestamped directory, then replaces the ..data link in a single rename, then removes the old directory. A rename is atomic, so the application sees either all the old files or all the new ones, never a mixture and never a half-written file.

Two practical consequences follow. A program that watches its configuration file for changes must watch the directory (or follow the link), because the file it opened is never modified, it is replaced. And the files are links owned by root with mode 0644 by default; set defaultMode on the volume when a program insists on something stricter.

Under the hood · How long an update takes, and why

The delay between editing a ConfigMap and seeing the new file has two parts: how quickly the kubelet learns about the change, and how soon it next syncs the Pod's volumes.

The first part depends on the kubelet's configMapAndSecretChangeDetectionStrategy. The default is Watch: the kubelet holds a watch on each ConfigMap its Pods use, so it hears about a change almost at once. The alternatives are Cache (ask again when a time-to-live expires) and Get (ask the API server every time).

The second part is the kubelet's periodic sync, about once a minute. So in a default cluster the new files appear within roughly a minute, sometimes a little more. In an exam task, do not wait and wonder: if the task needs the new value now, restart the Pods.

When the ConfigMap changes

What happens when the ConfigMap changeskubelet syncsthennothing happensfixMounted filesupdated in ~1 minApp rereadsor needs a signalConfigMap editedkubectl edit / applyEnv variableskeep the old valuerollout restartnew Pods, new values
What happens when the ConfigMap changes. Mounted files follow the ConfigMap within about a minute, but the application still has to read them again. Environment variables never change in a running container: only new Pods see the new values.

Parts:

  • Mounted files (updated in ~1 min)
  • App rereads (or needs a signal)
  • ConfigMap edited (kubectl edit / apply)
  • Env variables (keep the old value)
  • rollout restart (new Pods, new values)

Connections:

  • ConfigMap edited to Mounted files: kubelet syncs
  • Mounted files to App rereads: then
  • ConfigMap edited to Env variables: nothing happens
  • Env variables to rollout restart: fix

Editing a ConfigMap (kubectl edit cm, kubectl apply, kubectl patch) changes one object in etcd and nothing else. No Pod is restarted, and no rollout starts, because the Pod template has not changed. What the running containers see depends on how they consume it:

Consumed asAfter the edit
env / envFromNothing changes until the container is created again. A container that merely restarts in place (a crash, a failed probe) also picks up the new values, because the kubelet resolves the variables again each time it creates a container
VolumeFiles are replaced within about a minute. The application must read them again: some watch the file, some reload on a signal (nginx -s reload), many only read at start
Volume mounted with subPathNever updated. The file was bound once, when the container started
Immutable ConfigMapCannot be edited at all

So the dependable way to roll out a configuration change is to replace the Pods:

kubectl -n shop rollout restart deployment/web

This adds a timestamp annotation to the Pod template, which makes it a normal rolling update: new Pods come up with the new configuration before old ones go away, and kubectl rollout undo still works (though it brings back the old template, not the old ConfigMap contents).

Immutable ConfigMaps

apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config-v2
immutable: true
data:
  APP_MODE: production

immutable: true forbids every later change to data and binaryData, and the flag itself cannot be switched back. The only way to change such a ConfigMap is to delete it and create it again, and Pods that already mounted it should then be recreated too.

It buys two things. Nobody can break every running Pod with one careless kubectl edit. And the kubelet stops watching the object, which takes real load off the API server in clusters with tens of thousands of ConfigMaps.

It also fits a good habit: treat configuration as versioned. Create app-config-v2 next to app-config-v1 and change the name in the Deployment. Changing the name changes the Pod template, so the rollout happens by itself, and rolling back the Deployment brings back the old configuration as well. Kustomize's configMapGenerator does exactly this by adding a hash of the contents to the name.

Using it

Example · Create a ConfigMap four ways

From literal values, from a file, from a directory and from an env file:

# 1. Literals: one key per flag
kubectl -n shop create configmap app-config \
  --from-literal=APP_MODE=production --from-literal=LOG_LEVEL=info

# 2. A file: the key is the file name, the value is the whole file
kubectl -n shop create configmap web-conf --from-file=nginx.conf
kubectl -n shop create configmap web-conf2 --from-file=default.conf=nginx.conf   # choose the key yourself

# 3. A directory: one key per regular file in it
kubectl -n shop create configmap web-conf-all --from-file=conf.d/

# 4. An env file: one key per KEY=value line
kubectl -n shop create configmap app-env --from-env-file=app.env

Do not confuse 2 and 4. With --from-file=app.env you get one key called app.env whose value is the whole file; with --from-env-file=app.env you get one key per line, ready for envFrom.

Then look at what you made:

kubectl -n shop get cm                         # the DATA column counts the keys
kubectl -n shop describe cm app-config         # keys and values, readable
kubectl -n shop get cm app-config -o yaml      # the full object

Example · Give a Deployment all keys as environment variables

The Deployment web in namespace shop should receive every key of app-config as a variable.

Add an envFrom block to the container, with kubectl -n shop edit deployment web or in the manifest:

spec:
  template:
    spec:
      containers:
        - name: web
          image: nginx:1.29
          envFrom:
            - configMapRef:
                name: app-config

Changing the Pod template starts a rollout. Check the result in a new Pod:

kubectl -n shop rollout status deployment/web
kubectl -n shop exec deploy/web -- env | grep -E 'APP_MODE|LOG_LEVEL'
# APP_MODE=production
# LOG_LEVEL=info

There is also a one-line way, which writes one configMapKeyRef entry per key into the template for you:

kubectl -n shop set env deployment/web --from=configmap/app-config

Example · Mount a configuration file

nginx should serve with your own default.conf. Create the ConfigMap from the file, then mount it where nginx looks for site configuration:

kubectl -n shop create configmap web-conf --from-file=default.conf
apiVersion: v1
kind: Pod
metadata:
  name: web
  namespace: shop
spec:
  containers:
    - name: web
      image: nginx:1.29
      volumeMounts:
        - name: conf
          mountPath: /etc/nginx/conf.d
  volumes:
    - name: conf
      configMap:
        name: web-conf
kubectl -n shop exec web -- ls /etc/nginx/conf.d       # default.conf
kubectl -n shop exec web -- nginx -T | head            # the configuration nginx actually loaded

A mount covers whatever the image had in that directory. Here that is what you want: the image's own default.conf is replaced by yours. The next example is for when it is not.

Example · Pick keys, rename files, or add one file to a full directory

items chooses which keys become files and what the files are called. Keys you do not list are left out:

volumes:
  - name: conf
    configMap:
      name: app-config
      items:
        - key: app.properties
          path: application.properties     # the file name inside the mount
      defaultMode: 0440                    # permissions for the files (octal)

To place a single file into a directory that must keep its other files, mount with subPath:

volumeMounts:
  - name: conf
    mountPath: /etc/nginx/nginx.conf       # the full path of the one file
    subPath: nginx.conf                    # the key (file) inside the volume

Now /etc/nginx keeps mime.types and everything else from the image, and only nginx.conf comes from the ConfigMap. The price: a subPath mount is never refreshed, so a change needs new Pods.

Example · Change a value and roll it out

Set LOG_LEVEL to debug for the Deployment web, which reads it through envFrom.

kubectl -n shop patch configmap app-config --type merge -p '{"data":{"LOG_LEVEL":"debug"}}'
# or: kubectl -n shop edit configmap app-config

kubectl -n shop exec deploy/web -- printenv LOG_LEVEL      # still: info
kubectl -n shop rollout restart deployment/web
kubectl -n shop rollout status deployment/web
kubectl -n shop exec deploy/web -- printenv LOG_LEVEL      # now: debug

To replace a ConfigMap that was created from a file, generate the manifest again and apply it over the old one. kubectl create alone would fail with AlreadyExists:

kubectl -n shop create configmap web-conf --from-file=default.conf \
  --dry-run=client -o yaml | kubectl apply -f -

Tricks

Common mistakes

  • Expecting an edit to reach the application. Variables never change in a running container, subPath files never change, and even refreshed files help only if the application reads them again. When in doubt, kubectl rollout restart.
  • The ConfigMap is in another namespace. A Pod sees only the ConfigMaps of its own namespace. Creating the ConfigMap in default for a Pod in shop gives configmap "app-config" not found.
  • Unquoted numbers and booleans. data: { PORT: 8080 } is rejected because the value is not a string. Quote it: PORT: "8080". --from-literal never has this problem.
  • Mounting over a directory that was not empty. Mounting a volume at /etc/nginx hides mime.types and the rest, and nginx no longer starts. Mount at a directory you own, or mount one file with subPath.
  • Keys that cannot be variable names. With envFrom, a key that the kubelet does not accept as a variable name is skipped: the Pod starts, and an InvalidVariableNames event lists what was left out. Even when a key such as app.properties is accepted, a shell cannot read it as $app.properties. Keep file-like keys for volumes and use UPPER_SNAKE_CASE keys for variables.
  • Mismatched names inside the Pod. volumeMounts[].name must equal volumes[].name; the ConfigMap's own name goes under configMap.name. Three names, two of which must match.
  • Putting secrets in a ConfigMap. Values are plain text in kubectl describe, in etcd and in every backup. Passwords and tokens belong in a Secret.
  • Using a ConfigMap in a static Pod. A static Pod is run by the kubelet from a file, without the API server, so it cannot refer to ConfigMaps (or Secrets or ServiceAccounts). Control plane components take their settings from flags and host files instead.

Recap

  • A ConfigMap is keys and string values outside the image: namespaced, plain text, at most 1 MiB.
  • Three ways in: env + configMapKeyRef (one key), envFrom + configMapRef (all keys), or a configMap volume (keys as files).
  • The kubelet delivers it: variables once when the container is created, files continuously (except subPath).
  • Editing a ConfigMap restarts nothing. Use kubectl rollout restart, or a new ConfigMap name, to roll a change out.
  • CreateContainerConfigError or a FailedMount event means a ConfigMap or key is missing, misspelled or in another namespace.

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

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

Discussion

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