Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 78 ยท Configuration and Secrets

ConfigMaps

Learn Kubernetes ConfigMaps: create them from literals and files, inject as environment variables or mounted files, use immutable ConfigMaps, and know what updates.

A container image should be the same in development, staging and production. What changes between them is configuration: a database host, a log level, a feature flag, the contents of an nginx.conf. If you bake those values into the image you need a new image per environment, and every setting change becomes a rebuild. Kubernetes offers a separate object for this: the ConfigMap, a named bag of non-confidential key-value data that Pods can read.

In this lesson you will create ConfigMaps in several ways, deliver them to containers as environment variables or as files, see why one of those two delivery methods updates by itself and the other does not, and learn when to make a ConfigMap immutable. For passwords and tokens use a Secret instead; a ConfigMap offers no protection and is stored in plain text.

What a ConfigMap looks like

A ConfigMap has a data section of string keys and string values. Values can be short settings or whole files:

YAML
apiVersion: v1
kind: ConfigMap
metadata:
  name: shop-config
  namespace: shop
data:
  LOG_LEVEL: "info"
  DB_HOST: "postgres.shop.svc"
  app.properties: |
    cache.ttl=300
    feature.recommendations=true

Quote values like "info" and any numbers or booleans: every value is a string (see YAML and the Shape of a Manifest for the yes/no and number pitfalls). A key may contain letters, digits, -, _ and .. The total size is limited to 1 MiB, and there is a separate binaryData field (base64) for non-text content.

Creating ConfigMaps from the command line

For quick work, kubectl create configmap builds the object for you. These commands are read-only examples here, because the site has no cluster.

Terminal
# from literal key=value pairs
kubectl create configmap shop-config \
  --from-literal=LOG_LEVEL=info \
  --from-literal=DB_HOST=postgres.shop.svc

# from a file: the file name becomes the key, the contents the value
kubectl create configmap nginx-conf --from-file=nginx.conf

# from a file, with a custom key name
kubectl create configmap nginx-conf --from-file=default.conf=./nginx.conf

# from a directory: one key per file
kubectl create configmap site-config --from-file=./config/

# from an env file: each KEY=VALUE line becomes a key
kubectl create configmap shop-env --from-env-file=app.env

Add --dry-run=client -o yaml to any of them to print the manifest instead of creating it, then keep that YAML in version control. Inspect an existing one with kubectl get configmap shop-config -o yaml.

Two ways to deliver configuration

ConfigMap to container

Environment variables Read once when the container starts.
Mounted files Each key becomes a file in a directory.

Pick based on how your program reads configuration.

1 / 2

As environment variables

Pull single keys with configMapKeyRef, or import every key at once with envFrom:

YAML
apiVersion: v1
kind: Pod
metadata:
  name: shop-web
spec:
  containers:
    - name: web
      image: example/shop-web:1.4
      env:
        - name: LOG_LEVEL
          valueFrom:
            configMapKeyRef:
              name: shop-config
              key: LOG_LEVEL
      envFrom:
        - configMapRef:
            name: shop-env
          prefix: SHOP_

With envFrom every key becomes a variable; keys that are not valid variable names (for example app.properties) are skipped, and the Pod reports an event saying so. The optional prefix avoids collisions. If a referenced ConfigMap or key does not exist, the container fails to start with CreateContainerConfigError, unless you mark the reference optional: true. More on environment variables in Environment Variables and the Downward API.

As files in a volume

Mount the ConfigMap as a volume, and each key becomes a file named after the key:

YAML
apiVersion: v1
kind: Pod
metadata:
  name: shop-web
spec:
  containers:
    - name: web
      image: nginx:1.29
      volumeMounts:
        - name: conf
          mountPath: /etc/nginx/conf.d
          readOnly: true
  volumes:
    - name: conf
      configMap:
        name: nginx-conf
        items:
          - key: default.conf
            path: default.conf

Without items, every key is projected. With items you pick keys and choose file names. Mounting a ConfigMap over a directory hides whatever the image had there, which is why people mount into a dedicated directory such as /etc/nginx/conf.d. Volumes in general are covered in Volumes.

Update propagation

What happens when you edit a ConfigMap that running Pods use?

  • Environment variables never change in a running container. The values were copied in when the container started. Restart the Pods, for example with kubectl rollout restart deployment/shop-web.
  • Mounted files change eventually. The kubelet re-syncs ConfigMap volumes periodically and writes the new files atomically (it swaps a symlink, so a program never sees half a file). Expect a delay up to about a minute or more. Your program still has to notice the change: nginx needs a reload signal, many applications read files only at start.
  • subPath mounts do not update, because they bypass the symlink mechanism.

A very common pattern is to put a hash of the configuration into the Pod template (a label or annotation), so that a config change alters the template and triggers a normal rolling update. Helm and Kustomize can do this for you: Kustomize's configMapGenerator appends a content hash to the ConfigMap name, so changing the data creates a new ConfigMap and a new rollout.

Immutable ConfigMaps

Setting immutable: true locks the data:

YAML
apiVersion: v1
kind: ConfigMap
metadata:
  name: shop-config-v7
immutable: true
data:
  LOG_LEVEL: "info"

The API server then rejects changes to data and binaryData (you can only delete and recreate it, and you cannot make it mutable again). This protects you from an accidental edit breaking every Pod at once, and it lowers load on the API server in big clusters because the kubelet does not need to watch immutable ConfigMaps for changes. The usual workflow is versioned names (shop-config-v7) and updating the Deployment to point at the new one.

Simulating the two delivery methods

The real kubelet and container runtime are not available in the browser, so this stand-in models the behavior only: environment variables are a copy made at start, a volume is refreshed on a sync tick.

Python Env injection vs volume projection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The next stand-in turns a set of --from-literal, --from-file and --from-env-file inputs into the manifest kubectl would build, so you can see how the key names are chosen.

Python Building a ConfigMap like kubectl does

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Real ConfigMaps are validated by the API server (key characters, total size), and files are read from disk by kubectl; both parts are simplified here.

Practical advice

  • Keep one ConfigMap per concern (application settings, nginx config), not one giant one.
  • Give ConfigMaps the same labels as the app so they are easy to find and delete together.
  • Do not store secrets in them; anyone who can read the namespace can read them, and they appear in plain text in kubectl get -o yaml.
  • Prefer files for structured configuration and environment variables for a handful of simple settings, matching what your application already supports.
  • Ask for a restart, not a hope: if a setting matters, ensure something triggers a rollout when it changes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A running Pod reads LOG_LEVEL from a ConfigMap through an environment variable. You change the ConfigMap. What does the container see?

    Environment variables are copied into the container when it starts. Only a restart (for example a rollout restart) picks up the new value.
  2. 2. Which mounting choice means the mounted file will NOT refresh when the ConfigMap changes?

    subPath mounts bypass the symlink mechanism the kubelet uses for atomic updates, so they stay as they were at start.
  3. 3. What does immutable: true on a ConfigMap do?

    The API server rejects edits to the data of an immutable ConfigMap, and kubelets do not need to watch it for changes.
  4. 4. A Pod is stuck with CreateContainerConfigError after you added a configMapKeyRef. What is a likely cause?

    A missing ConfigMap or key makes the container impossible to configure. Fix the name or add optional: true.

Summary

  • A ConfigMap holds non-confidential configuration as string key-value pairs (up to 1 MiB), keeping images identical across environments.
  • Create it from literals, files, directories or env files, or write the YAML and keep it in version control.
  • Deliver it as environment variables (read once at start) or as files in a volume (refreshed by the kubelet, except with subPath).
  • Trigger a rollout when configuration changes, for example with hashed names or a template annotation.
  • immutable: true protects against accidental edits; use versioned names to roll changes out.

Passwords, tokens and keys need more care. Continue with Secrets.