Kubernetes: ConfigMap, Secret, variables and volumes
Pod settings and data — ConfigMap and Secret, env and envFrom, configMap/secret/emptyDir/PVC/hostPath volumes, subPath
There's one container image for all environments, but the settings differ. Kubernetes stores them separately from the image and passes them into the container in two ways — as environment variables or as files in a mounted volume.
| Object | What it stores |
|---|---|
| ConfigMap | regular settings: key → string (or the contents of a whole file) |
| Secret | passwords, tokens, certificates; the same "key → value", but values are base64 and access is usually restricted by RBAC |
| PersistentVolumeClaim (PVC) | a request for a persistent disk that survives pod restarts |
Syntax
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
MODE: production
app.conf: |
listen 8080
workers 4
---
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
containers:
- name: app
image: busybox:1.36
command: ["sh", "-c", "echo $MODE; cat /etc/app/app.conf; sleep 3600"]
env:
- name: MODE
valueFrom:
configMapKeyRef: {name: app-config, key: MODE}
volumeMounts:
- name: config
mountPath: /etc/app
volumes:
- name: config
configMap:
name: app-config
ConfigMap and Secret
| Field | Meaning | Notes |
|---|---|---|
data (ConfigMap) | key → string | values are strings only: "3", "true" in quotes |
binaryData (ConfigMap) | key → binary data in base64 | |
data (Secret) | key → value in base64 | echo -n 'pass' | base64 |
stringData (Secret) | key → value in plain text | encoded into data on save; a key from stringData overrides the same key in data |
type (Secret) | Opaque — arbitrary data; kubernetes.io/tls — keys tls.crt, tls.key; kubernetes.io/dockerconfigjson — registry access; kubernetes.io/basic-auth — username, password | Opaque |
immutable | true — values can no longer be changed, only the object recreated | false |
Keys are Latin letters, digits, -, _, .. One object can be up to 1 MiB.
Environment variables
Fields of a containers[] element:
| Field | Meaning |
|---|---|
env[].name + value | a variable with an explicit value (a string) |
env[].valueFrom.configMapKeyRef | {name: configmap, key: key, optional: true} — the value of one ConfigMap key |
env[].valueFrom.secretKeyRef | {name: secret, key: key} — a value from a Secret (already decoded) |
env[].valueFrom.fieldRef.fieldPath | data about the pod itself: metadata.name, metadata.namespace, metadata.labels['app'], status.podIP, spec.nodeName, spec.serviceAccountName |
env[].valueFrom.resourceFieldRef | {containerName, resource: limits.memory} — the container's own resources |
envFrom[].configMapRef.name | all ConfigMap keys as variables |
envFrom[].secretRef.name | all Secret keys as variables |
envFrom[].prefix | a prefix for the names: prefix: DB_ gives DB_HOST |
In value, command and args you can reference variables declared above: $(MODE). If a variable name is in both env and envFrom, env wins.
Volumes
Volumes are declared at the pod level in spec.volumes[] and mounted into each container via volumeMounts[], by name.
Type in volumes[] | What it is | Main fields |
|---|---|---|
configMap | ConfigMap keys as files | name, items: [{key, path}] — pick keys and file names, defaultMode — file permissions (default 0644), optional |
secret | Secret keys as files (decoded) | secretName (not name!), items, defaultMode |
emptyDir | an empty directory for the lifetime of the pod; shared by its containers | medium: Memory — in RAM (tmpfs), sizeLimit: 100Mi |
persistentVolumeClaim | a persistent disk via a PVC | claimName, readOnly |
hostPath | a directory or file on the node | path, type: Directory | DirectoryOrCreate | File | FileOrCreate | Socket |
projected | several sources (configMap, secret, downwardAPI, token) in one directory | sources: […] |
downwardAPI | labels, annotations, pod name as files | items: [{path, fieldRef}] |
volumeMounts[] fields:
| Field | Meaning | Default / notes |
|---|---|---|
name | volume name from volumes | required |
mountPath | where to mount in the container | required; hides whatever was in that image directory |
subPath | mount only one file/subdirectory of the volume | the image directory's contents aren't hidden, but the file is not updated when the ConfigMap/Secret changes |
readOnly | read-only | false (configMap and secret are read-only anyway) |
PersistentVolumeClaim
| Field | Meaning | Default / notes |
|---|---|---|
spec.accessModes | ReadWriteOnce (RWO) — write from one node; ReadOnlyMany (ROX); ReadWriteMany (RWX) — write from many nodes; ReadWriteOncePod — a single pod only | required in practice; not all storage supports RWX |
spec.resources.requests.storage | size: 1Gi, 500Mi | |
spec.storageClassName | storage class (standard, gp3, …) | omitted — the default class; "" — no dynamic provisioning |
spec.volumeMode | Filesystem / Block | Filesystem |
A PVC is a request; the disk itself (PersistentVolume) is created for it by the storage class's provisioner. For a StatefulSet, claims are defined via volumeClaimTemplates (see k8s-workloads).
Examples
# ConfigMap: keys from literals and from a file (key = file name or explicit)
printf 'listen 8080\nworkers 4\n' > app.conf
kubectl create configmap app-config --from-literal=MODE=production \
--from-file=app.conf --dry-run=client -o yaml > cm.yaml
# ConfigMap from an env file: KEY=VALUE lines become keys
printf 'MODE=production\nLOG_LEVEL=info\n' > app.env
kubectl create configmap app-env --from-env-file=app.env --dry-run=client -o yaml
# Secret: kubectl encodes the values to base64 itself
kubectl create secret generic db-cred --from-literal=username=app \
--from-literal=password='s3cr3t!' --dry-run=client -o yaml > secret.yaml
# read a value back
yq '.data.password' secret.yaml | base64 -d; echo
# encode by hand — always with -n, otherwise \n ends up in the value
echo -n 's3cr3t!' | base64
# a TLS secret for Ingress from a certificate/key pair
openssl req -x509 -newkey rsa:2048 -nodes -days 30 -subj '/CN=example.com' \
-keyout tls.key -out tls.crt 2>/dev/null
kubectl create secret tls site-tls --cert=tls.crt --key=tls.key --dry-run=client -o yaml > tls.yaml
# attach all ConfigMap keys to a Deployment as variables (via yq:
# `kubectl set env --from=configmap/…` needs a cluster)
kubectl create deployment web --image=nginx:1.27 --dry-run=client -o yaml \
| yq '.spec.template.spec.containers[0].envFrom = [{"configMapRef": {"name": "app-config"}}]' > deploy.yaml
kubeconform -strict -summary cm.yaml secret.yaml tls.yaml deploy.yaml
A Secret with stringData and how to use it: one variable, all keys with a prefix, and files with 0400 permissions:
apiVersion: v1
kind: Secret
metadata:
name: db-cred
type: Opaque
stringData: # plain text; data will hold base64
username: app
password: "s3cr3t!"
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
spec:
selector:
matchLabels: {app: api}
template:
metadata:
labels: {app: api}
spec:
containers:
- name: api
image: registry.example.com/api:2.0
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef: {name: db-cred, key: password}
- name: POD_NAME
valueFrom:
fieldRef: {fieldPath: metadata.name}
- name: DSN
value: "postgres://app:$(DB_PASSWORD)@db:5432/app"
envFrom:
- secretRef: {name: db-cred}
prefix: DB_ # DB_username, DB_password
volumeMounts:
- name: creds
mountPath: /run/secrets/db
readOnly: true
volumes:
- name: creds
secret:
secretName: db-cred
defaultMode: 0400
One file from a ConfigMap on top of an image directory, a shared emptyDir and a persistent disk:
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: uploads
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 5Gi
---
apiVersion: v1
kind: Pod
metadata:
name: web
spec:
containers:
- name: nginx
image: nginx:1.27
volumeMounts:
- name: config
mountPath: /etc/nginx/conf.d/site.conf # only this file
subPath: site.conf
- name: cache
mountPath: /var/cache/nginx
- name: uploads
mountPath: /srv/uploads
volumes:
- name: config
configMap:
name: nginx-config
items:
- {key: site.conf, path: site.conf}
- name: cache
emptyDir:
sizeLimit: 200Mi
- name: uploads
persistentVolumeClaim:
claimName: uploads
Pitfalls
- A Secret doesn't encrypt. base64 is an encoding;
base64 -dreads it without a key. What protects it is access control (RBAC), not the format. Don't commit Secret manifests with real values to git. echo 'pass' | base64without-nalso encodes the newline: the password gets an extra\n, and logging in "inexplicably" fails.- A Secret's
dataholds only base64. The API server rejects a plain-text value indata(illegal base64 data), whilekubeconformlets it through. For plain text there'sstringData. defaultModefile permissions are octal.kubectlreads0400as an octal number (256), while YAML 1.2 tools read it as decimal 400:yq -o jsonturns it into400, i.e. different permissions. In JSON manifests write the decimal value:256for0400,420for0644.- Numbers and booleans in a ConfigMap's
datamust be quoted:PORT: "8080",DEBUG: "true". Without quoteskubeconformreturnsexpected string, but got number. - Environment variables don't update. You changed the ConfigMap — the container sees the old values until the pod restarts. Files in a volume update on their own (with a delay of up to a minute or two), but not with
subPath. mountPathon an existing directory hides everything the image had there. Mount a ConfigMap at/etc/nginxand the image'snginx.confis gone. For a single file usesubPath.secretName, notname. For aconfigMapvolume the field is calledname, for asecretvolume it'ssecretName. Mix them up and the schema repliesadditionalProperties 'name' not allowed.--from-env-filecan't be combined with--from-literaland--from-filein onekubectl create configmapcommand.- ConfigMap or Secret not created yet — the pod won't start (
CreateContainerConfigError) until the object appears. If the object is optional, setoptional: true. hostPathties the pod to a node and gives access to its filesystem. A pod on another node sees different data; in shared clustershostPathis often forbidden by policy.emptyDirlives as long as the pod. A container restart keeps the data, but recreating the pod (a rollout, moving to another node) wipes it.- A
ReadWriteOncePVC and several Deployment replicas — a second pod on another node can't attach the disk and hangs inContainerCreating. A StatefulSet gives each replica its own disk.
See also
kubectl · kubeconform · yq · base64 · openssl · env · k8s-workloads · k8s-networking · k8s-rbac