kubernetes

Kubernetes ConfigMap

Kubernetes ConfigMap Explained: Managing Application Configuration

By Shubhankar Tripathi • • 5 min read

Kubernetes ConfigMap Explained: Managing Application Configuration

bitcodematrix.com | Kubernetes Series

1. Introduction

The same container image should run unchanged in development, staging and production. What differs between those environments, such as database addresses, feature flags, log levels and file-based settings, is configuration. Kubernetes provides a dedicated API object for it: the ConfigMap. It stores non-sensitive configuration outside the image and delivers it to Pods as environment variables, command-line arguments or files.

This article explains how ConfigMaps work from the ground up. You will learn how to create them in several ways, how Pods consume them, what updates and what does not, how immutable ConfigMaps and versioned names support safe rollouts, how to manage them across environments, how they differ from Secrets, and how to troubleshoot the typical problems. It complements the article on emptyDir, ConfigMap and Secret volumes, with a focus on configuration management.

2. Why Externalise Configuration?

Baking configuration into a container image causes several problems. Every change requires a new image build, each environment needs its own image, and the image that you tested is not the image that you deploy. Externalising configuration solves these issues and follows the widely used principle of strictly separating configuration from code.

  • One image, many environments. The artefact that passes testing is the one that runs in production, with only its configuration changed.

  • Faster changes. Changing a setting does not require rebuilding or re-scanning an image.

  • Clear ownership and review. Configuration lives in version control as Kubernetes manifests, with a reviewable history.

  • Reuse. Several workloads can share the same ConfigMap, for example common endpoints or feature flags.

The trade-off is that configuration now has its own lifecycle, which you must manage deliberately. The sections below show how.

3. Anatomy of a ConfigMap

apiVersion: v1

kind: ConfigMap

metadata:

  name: web-config

  namespace: shop

data:

  LOG_LEVEL: info

  CACHE_TTL_SECONDS: "300"

  app.properties: |

    server.port=8080

    feature.checkout=true

binaryData:

  logo.bin: aGVsbG8=

immutable: false

Field

Meaning

data

Key-value pairs with UTF-8 text values. A value can be a single setting or the entire content of a file

binaryData

Key-value pairs for binary content, with values encoded in base64 in the manifest

immutable

When true, the data can no longer be changed. The object can only be deleted and recreated

 

A few rules apply to every ConfigMap:

  • Namespaced. A ConfigMap lives in one namespace and can be referenced only by Pods in that namespace.

  • Key names. Keys may contain letters, digits, dashes, underscores and dots, up to 253 characters. When used as environment variables, they must also be valid variable names.

  • Size. The total data in a ConfigMap cannot exceed about 1 MiB. This is a limit of the underlying storage, and it makes ConfigMaps unsuitable for large files or datasets.

  • No schema. Kubernetes treats values as opaque strings. It does not validate that your configuration file is correct.

  • Not confidential. ConfigMap data is stored and returned in plain text. Never put passwords, tokens or keys in it; use a Secret.

Values that look like numbers or booleans must be quoted in YAML, as in "300" above, because ConfigMap values are strings.

4. Creating ConfigMaps

There are four common ways to create a ConfigMap, and they suit different situations.

Method

Command or approach

Resulting keys

From literals

kubectl create configmap web-config --from-literal=LOG_LEVEL=info

One key per literal

From a file

kubectl create configmap web-config --from-file=app.properties

Key is the file name, value is the file content

From a file with a chosen key

kubectl create configmap web-config --from-file=settings=app.properties

Key is settings

From a directory

kubectl create configmap web-config --from-file=./config/

One key per file in the directory (not recursive)

From an env file

kubectl create configmap web-config --from-env-file=app.env

One key per KEY=value line

From a manifest

kubectl apply -f configmap.yaml

Exactly what you write

 

For anything beyond experiments, prefer manifests in version control. To generate a manifest from files or literals without creating anything in the cluster, use a dry run and capture the output:

kubectl create configmap web-config -n shop \

  --from-file=app.properties --from-literal=LOG_LEVEL=info \

  --dry-run=client -o yaml > web-config.yaml

Tools such as Kustomize and Helm can also generate ConfigMaps from files, which is covered in Section 9.

5. Consuming ConfigMaps in Pods

A Pod can use a ConfigMap in several ways. The following Deployment shows the most common ones side by side:

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: web

        image: nginx:1.27

        env:

        - name: LOG_LEVEL

          valueFrom:

            configMapKeyRef:

              name: web-config

              key: LOG_LEVEL

        envFrom:

        - configMapRef:

            name: web-feature-flags

          prefix: FEATURE_

        volumeMounts:

        - name: config

          mountPath: /etc/web

          readOnly: true

      volumes:

      - name: config

        configMap:

          name: web-config

          items:

          - key: app.properties

            path: app.properties

5.1 A Single Key as an Environment Variable

The env section with configMapKeyRef injects one key as one variable. You choose the variable name, which can differ from the key. Add optional: true to the reference if the Pod should start even when the ConfigMap or key is missing.

5.2 All Keys as Environment Variables

The envFrom section with configMapRef injects every key as a variable. The optional prefix keeps names from colliding, here turning a key such as CHECKOUT into FEATURE_CHECKOUT. Keys that are not valid variable names are skipped, and Kubernetes records an event to tell you so.

If the same name is defined more than once, the order of precedence is simple: variables defined explicitly under env override those from envFrom, and when several envFrom sources define the same key, the last one wins.

5.3 Command-Line Arguments

Environment variables can be used in the command or arguments with the $(NAME) syntax, which Kubernetes expands before starting the container:

command: ["/app/server"]

args: ["--log-level=$(LOG_LEVEL)"]

This works only for variables that are defined in the container's env or envFrom, so first inject the value as a variable.

5.4 Files in a Volume

A configMap volume turns each key into a file. This is the right choice for configuration files such as nginx.conf, application.yaml or properties files. With items, you can select specific keys and rename them as files, and with defaultMode you can set permissions. The files are mounted read-only.

5.5 Reading the API Directly

An application can also read a ConfigMap through the Kubernetes API with a client library, which allows it to watch for changes. This requires a ServiceAccount with RBAC permission to read the object, couples the application to Kubernetes, and is rarely necessary. Prefer environment variables or mounted files unless you have a specific need.

6. Environment Variables or Files?

Aspect

Environment variables

Mounted files

Best suited to

A small number of simple settings

Configuration files, structured or multi-line content

Updated in running Pods

No. Values are fixed when the container starts

Yes, with a delay, except subPath mounts

Application changes needed

None for twelve-factor style apps

The app must read from a path, and may need to reload

Name constraints

Keys must be valid variable names

Keys become file names

Large values

Awkward

Natural

Visibility

Inherited by child processes and visible in diagnostics

Controlled by file permissions

 

A common and sensible split is to use environment variables for scalar settings such as endpoints and flags, and files for anything that is naturally a file. Some applications let you choose either, in which case files give you update propagation and cleaner separation.

7. What Happens When a ConfigMap Changes

Updating a ConfigMap does not automatically restart the Pods that use it. What the running Pods see depends on how they consume it:

Consumption method

Effect of an update

Environment variable (env or envFrom)

No change in running containers. New values apply only when the container is restarted or the Pod is recreated

Command-line argument

No change; arguments are fixed at start

Volume mount

The files are refreshed by the kubelet after a delay, typically within a minute or two

Volume mount with subPath

No change; the file stays as it was at start

Immutable ConfigMap

The ConfigMap cannot be updated at all

 

Even when files are refreshed, the application sees the change only if it re-reads them. Many programs read configuration once at start-up. To roll out a configuration change reliably, use one of these approaches:

  • Rolling restart. Run kubectl rollout restart deployment/web after changing the ConfigMap. This is simple, predictable and works with any application.

  • Hash in the Pod template. Put a checksum of the configuration into a Pod template annotation, so any change creates a new ReplicaSet and a rolling update. Helm charts commonly do this.

  • Versioned names. Give each version of the ConfigMap a new name and update the Deployment to point to it, which is a normal template change that triggers a rollout and keeps the old version for rollback.

  • In-process reload. Let the application watch its files or accept a reload signal, possibly through a sidecar. This avoids restarts but needs application support and careful testing.

A subtle risk deserves attention. If you edit a ConfigMap in place and a Pod is later rescheduled or scaled up, the new Pod picks up the new configuration while older Pods still run with the old one. This mixed state can be hard to diagnose, and it is another reason to prefer rollouts tied to configuration changes.

8. Immutable ConfigMaps and Versioning

Setting immutable to true locks a ConfigMap. The data can never be changed again, and the field itself cannot be reverted. To change the configuration, you create a new ConfigMap. Immutability brings two benefits:

  • Safety. It prevents accidental or malicious edits that could break every Pod that uses the object at the next restart.

  • Performance. The kubelet no longer needs to watch immutable ConfigMaps for changes, which reduces load on the API server in clusters with many of them.

The natural companion is versioned naming. Instead of editing web-config, create web-config-v2, update the Deployment to refer to it and let the rolling update proceed. Rollback is simply pointing the Deployment back at web-config-v1. Clean up old versions that no Pod uses, on a schedule.

8.1 Kustomize Generators

Doing this by hand is tedious, and Kustomize automates it. A configMapGenerator creates a ConfigMap whose name includes a hash of its content, and it rewrites references to it in the other resources of the same kustomization:

apiVersion: kustomize.config.k8s.io/v1beta1

kind: Kustomization

resources:

- deployment.yaml

configMapGenerator:

- name: web-config

  files:

  - app.properties

  literals:

  - LOG_LEVEL=info

The output has a name such as web-config-7b9c4k2f5d, and the Deployment refers to that name. Any change to the content produces a new hash, a new ConfigMap and, automatically, a rolling update. This pattern gives you immutability-style safety without manual renaming.

9. Managing ConfigMaps Across Environments

Real applications need different configuration in development, staging and production. Three practices keep this manageable:

  • Overlays or values files. With Kustomize, keep a base ConfigMap and override specific keys in per-environment overlays. With Helm, expose settings as chart values and provide a values file per environment.

  • Everything in Git. Store ConfigMaps as manifests next to the code they configure, and deploy them through a GitOps or CI/CD pipeline, so that the live state always matches a reviewed commit.

  • Consistent names and labels. Use the same ConfigMap names in every environment, with app and environment labels, so that manifests stay portable and tooling can find related objects.

Keep differences between environments small and explicit. A ConfigMap that has dozens of environment-specific keys is a sign that you should split it, or that the application needs a better configuration model.

9.1 Structuring ConfigMaps

Guideline

Reason

One ConfigMap per application or component

Clear ownership and focused changes

Separate shared configuration into its own ConfigMap

Avoids duplication, but keep the number of consumers manageable

Keep files and simple settings in separate ConfigMaps if their lifecycles differ

A feature-flag change should not touch the main configuration file

Avoid one giant ConfigMap for everything

Hits the size limit, increases blast radius and makes diffs noisy

Prefix keys or use clear naming

Prevents collisions with envFrom and improves readability

 

9.2 Validating Configuration

Kubernetes validates that a ConfigMap is well formed, but not that its content is meaningful. A typo in a nested YAML file is accepted happily and fails at runtime. Reduce this risk by validating configuration in your pipeline: lint the manifests, check the embedded configuration files with the application's own validation command if it has one, and test the rendered output of Helm or Kustomize in a staging cluster before production. Admission policies can enforce rules, such as requiring labels or forbidding certain keys.

10. Hands-On Walkthrough

This exercise shows the difference between environment variables and mounted files when a ConfigMap changes.

  1. Create the ConfigMap and a Pod that uses it both ways.

kubectl create configmap demo-config -n shop \

  --from-literal=GREETING=hello \

  --from-literal=message.txt=hello

apiVersion: v1

kind: Pod

metadata:

  name: cm-demo

  namespace: shop

spec:

  containers:

  - name: app

    image: busybox:1.36

    command: ["sh", "-c", "sleep 3600"]

    env:

    - name: GREETING

      valueFrom:

        configMapKeyRef:

          name: demo-config

          key: GREETING

    volumeMounts:

    - name: cfg

      mountPath: /etc/demo

  volumes:

  - name: cfg

    configMap:

      name: demo-config

  1. Check both values inside the Pod.

kubectl exec cm-demo -n shop -- sh -c 'echo $GREETING; cat /etc/demo/message.txt'

  1. Change the ConfigMap.

kubectl patch configmap demo-config -n shop \

  -p '{"data":{"GREETING":"bonjour","message.txt":"bonjour"}}'

  1. Wait a minute or two, then check again.

kubectl exec cm-demo -n shop -- sh -c 'echo $GREETING; cat /etc/demo/message.txt'

The environment variable still prints the old value, while the file shows the new one. Recreate the Pod and both show the new value. The same experiment with subPath for the file would show that it also stays unchanged.

  1. Clean up.

kubectl delete pod cm-demo -n shop

kubectl delete configmap demo-config -n shop

11. ConfigMap or Secret?

Aspect

ConfigMap

Secret

Intended content

Non-sensitive settings and files

Passwords, tokens, keys, certificates

Storage in the API

Plain text

Base64-encoded, which is not encryption; can be encrypted at rest when configured

On the node when mounted

Files managed by the kubelet

Held in memory (tmpfs)

Access control

Often readable by many

Should have tighter RBAC

Size limit

About 1 MiB

About 1 MiB

 

The rule is straightforward: if the value would cause harm when disclosed, it does not belong in a ConfigMap. A connection string without a password is configuration, but the password is a secret. If an application takes one file that mixes both, store the file in a Secret, or assemble it from both sources at start-up with an init container.

12. Security and Access Control

  • Plain-text visibility. Anyone with read access to ConfigMaps in a namespace can see all their content. Review who has get, list and watch permissions, and remember that list returns the data of every ConfigMap.

  • Write access is powerful. Changing a ConfigMap can change the behaviour of every Pod that uses it, for example by altering an endpoint or disabling a security feature. Restrict update and patch permissions and review changes.

  • Do not store secrets. Scanning your repository and cluster for credentials in ConfigMaps is a worthwhile control, and admission policies can block obvious patterns.

  • System ConfigMaps. Clusters contain ConfigMaps maintained by Kubernetes and add-ons, for example the CA bundle that is published in each namespace, and the CoreDNS and kube-proxy configuration in kube-system. Leave these to their owners and be careful when granting broad write access to system namespaces.

  • Immutability as a control. Making production ConfigMaps immutable stops in-place tampering and forces changes through a deployment.

  • Audit. Enable audit logging for ConfigMap changes in production, so that you can answer who changed what and when.

13. Limits and Gotchas

Gotcha

Detail

Size limit

About 1 MiB per ConfigMap. Large content belongs in a volume, an image or an external store

Missing reference with env

The container fails with CreateContainerConfigError until the ConfigMap or key exists, unless the reference is optional

Missing reference with a volume

The Pod stays in ContainerCreating with a mount failure event, unless the volume is optional

Invalid keys with envFrom

Keys that are not valid variable names are skipped, with an event as the only clue

Numbers and booleans

Values are strings. Quote them in YAML and parse them in the application

Mounting over a directory

The mount hides existing files in that path. Use a dedicated directory or subPath

subPath

Files mounted with subPath never update

Symbolic links

Mounted files are symlinks into a hidden directory, which can confuse some tools

Same namespace only

A Pod cannot reference a ConfigMap in another namespace. Replicate the object where needed

Update does not restart Pods

Plan a rollout mechanism for every configuration change

Mixed configuration versions

Old and new Pods can run different configuration after an in-place edit and a scale-up

 

14. Troubleshooting

kubectl get configmap -n shop

kubectl describe configmap web-config -n shop

kubectl get configmap web-config -n shop -o yaml

kubectl describe pod <pod> -n shop

kubectl exec <pod> -n shop -- env | sort

kubectl exec <pod> -n shop -- ls -la /etc/web

Symptom

Likely cause and check

Pod in CreateContainerConfigError

A referenced ConfigMap or key is missing. Compare the names in the Pod spec with kubectl get configmap, check the namespace, or set optional

Pod in ContainerCreating with a mount error

A ConfigMap volume refers to an object that does not exist, or the node cannot fetch it. Read the Pod events

Application still uses old settings

The value came from an environment variable, a subPath mount, or the application only reads configuration at start-up. Restart the Pods or add a reload mechanism

Some Pods have different settings

In-place edit followed by scale-up or rescheduling. Roll out all Pods, and use versioned or hashed names

Expected environment variable is missing

The key is not a valid variable name, was skipped by envFrom, or a prefix changed the name. Check the Pod events and the env output

The ConfigMap cannot be edited

It is immutable. Create a new version and update references

Mounted config file not found

The key name differs from the path expected by the application, items renamed it, or the mount hides a directory. List the mount

Configuration file parsing errors

Indentation or syntax errors in the embedded file. Validate the file outside the cluster

kubectl apply fails with an annotation size error

Large ConfigMaps can exceed the limit of the last-applied annotation. Use server-side apply or create/replace

Config changes appear late

Normal delay for volume propagation. Wait, and do not depend on instant updates

 

15. Best Practices

  • Keep configuration out of images, and keep ConfigMaps in version control with reviews.

  • Use ConfigMaps only for non-sensitive data, and Secrets or an external secret manager for everything sensitive.

  • Use environment variables for simple scalar settings and mounted files for real configuration files.

  • Tie every configuration change to a rollout, with versioned names, generated hash suffixes or checksum annotations.

  • Make production ConfigMaps immutable where practical, and clean up old versions.

  • Quote numbers and booleans in YAML and validate configuration content in CI before it reaches the cluster.

  • Keep ConfigMaps small, focused and well named, and split by lifecycle and ownership.

  • Use optional references deliberately, because a silently missing setting can be worse than a failed start.

  • Restrict write access to ConfigMaps, enable audit logging, and review changes like code.

  • Test changes in staging, including the rollout and the application's behaviour with the new values.

16. Conclusion

A ConfigMap is a simple object with a clear job: it carries non-sensitive configuration from the cluster to your Pods, so that one image can serve every environment. Its simplicity hides a few behaviours that you must know, in particular that environment variables never update, that mounted files update with a delay and not at all through subPath, and that nothing restarts your Pods for you.

Combine ConfigMaps with a disciplined workflow: manifests in Git, validation in CI, versioned or hashed names, rollouts tied to changes, and strict separation from Secrets. With those habits, configuration changes become routine, reviewable and safe, which is exactly what you want from the settings that control your applications.