ConfigMaps
Good container images are environment-agnostic: the same image runs in dev, staging and production. What changes (log level, feature flags, URLs, whole config files) is injected at start-up. A ConfigMap holds that non-secret configuration as key/value pairs.
apiVersion: v1
kind: ConfigMap
metadata:
name: api-config
data:
LOG_LEVEL: info
FEATURE_CHECKOUT_V2: "true" # values are always strings
DATABASE_HOST: db.shop.svc.cluster.local
app.properties: | # a whole file as one key
cache.ttl=300
payments.provider=stripekubectl create configmap api-config --from-literal=LOG_LEVEL=info --from-file=app.properties
kubectl get configmap api-config -o yamlConfigMaps are limited to 1 MiB. Bigger data belongs in a volume or object storage.
Three ways to consume a ConfigMap
spec:
containers:
- name: api
image: ghcr.io/acme/api:2.3.1
env:
- name: LOG_LEVEL # 1. one key -> one variable
valueFrom:
configMapKeyRef: {name: api-config, key: LOG_LEVEL}
envFrom:
- configMapRef: {name: api-config} # 2. every key -> a variable
prefix: CFG_
volumeMounts:
- name: config
mountPath: /etc/api # 3. every key -> a file
readOnly: true
volumes:
- name: config
configMap:
name: api-config
items: # optional: only some keys, custom file names
- {key: app.properties, path: app.properties}This model builds a container's environment from a ConfigMap the way the kubelet does. Keys that aren't valid variable names are skipped by envFrom (and reported as an event), and explicit env entries override envFrom:
import re
import yaml
cm = yaml.safe_load("""
data:
LOG_LEVEL: info
FEATURE_CHECKOUT_V2: "true"
DATABASE_HOST: db.shop.svc.cluster.local
app.properties: |
cache.ttl=300
""")["data"]
container = {
"envFrom": [{"prefix": "CFG_"}],
"env": [{"name": "CFG_LOG_LEVEL", "value": "debug"}],
}
VALID = re.compile(r"^[-._a-zA-Z][-._a-zA-Z0-9]*quot;)
environment, skipped = {}, []
for source in container["envFrom"]:
for key, value in cm.items():
name = source.get("prefix", "") + key
if VALID.match(name) and "." not in name:
environment[name] = value
else:
skipped.append(key)
for e in container["env"]:
environment[e["name"]] = e["value"]
for k in sorted(environment):
print(f"{k}={environment[k]}")
print("skipped keys:", skipped)CFG_DATABASE_HOST=db.shop.svc.cluster.local
CFG_FEATURE_CHECKOUT_V2=true
CFG_LOG_LEVEL=debug
skipped keys: ['app.properties']
Note: The real rule is slightly more permissive (names may contain
.and-in newer versions), but many programs can't read such variables, so stick toUPPER_SNAKE_CASEkeys for env use and dotted names for files.
Updates: env vs files
| Consumed as | When the ConfigMap changes |
|---|---|
| Environment variables | Nothing happens until the Pod restarts |
| Mounted volume | Files are updated in place after a short delay (kubelet sync, ~1 minute) |
Mounted with subPath |
Never updated |
The app still has to notice changed files. A common pattern is to make the config part of the Pod template so that every change triggers a rolling update: include a hash of the ConfigMap as an annotation (Helm charts and Kustomize do this for you).
import hashlib
import json
def checksum(data):
return hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest()[:12]
v1 = {"LOG_LEVEL": "info", "FEATURE_CHECKOUT_V2": "true"}
v2 = {"LOG_LEVEL": "debug", "FEATURE_CHECKOUT_V2": "true"}
for label, data in [("v1", v1), ("v1 (re-applied)", dict(v1)), ("v2", v2)]:
annotation = {"checksum/config": checksum(data)}
print(f"{label:16} template annotation {annotation}")
print("v1 -> v2 changes the Pod template:", checksum(v1) != checksum(v2))v1 template annotation {'checksum/config': '933f5da4d3a0'}
v1 (re-applied) template annotation {'checksum/config': '933f5da4d3a0'}
v2 template annotation {'checksum/config': '5c30b5c56ec1'}
v1 -> v2 changes the Pod template: True
Immutable ConfigMaps
Set immutable: true to forbid changes. The kubelet then stops watching it (less API load in big clusters), and a bad edit can't silently reach running Pods: you create api-config-v2 and point the Deployment at it, which is an ordinary, reversible rollout.
apiVersion: v1
kind: ConfigMap
metadata:
name: api-config-v2
immutable: true
data:
LOG_LEVEL: warnMounted files
When mounted as a volume, each key becomes a file named after the key. Behind the scenes the kubelet writes a timestamped directory and flips a ..data symlink, which is how updates appear atomically:
/etc/api/
├── ..2026_01_15_10_00_00.123456789/
│ ├── LOG_LEVEL
│ └── app.properties
├── ..data -> ..2026_01_15_10_00_00.123456789
├── LOG_LEVEL -> ..data/LOG_LEVEL
└── app.properties -> ..data/app.propertiesTest yourself
A ConfigMap used through envFrom is updated. When does the running container see the new values?
- Immediately
- After about a minute
- Only after the Pod restarts
- Never, ConfigMaps can't change
What is the size limit of a ConfigMap?
- 1 KiB
- 64 KiB
- 1 MiB
- 1 GiB
Which approach forces a rolling update whenever config changes?
- Mounting with subPath
- Putting a hash of the ConfigMap in a Pod template annotation
- Using kubectl get
- Setting restartPolicy: Never