← Full reference

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.

ObjectWhat it stores
ConfigMapregular settings: key → string (or the contents of a whole file)
Secretpasswords, 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

FieldMeaningNotes
data (ConfigMap)key → stringvalues are strings only: "3", "true" in quotes
binaryData (ConfigMap)key → binary data in base64
data (Secret)key → value in base64echo -n 'pass' | base64
stringData (Secret)key → value in plain textencoded 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, passwordOpaque
immutabletrue — values can no longer be changed, only the object recreatedfalse

Keys are Latin letters, digits, -, _, .. One object can be up to 1 MiB.

Environment variables

Fields of a containers[] element:

FieldMeaning
env[].name + valuea 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.fieldPathdata 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.nameall ConfigMap keys as variables
envFrom[].secretRef.nameall Secret keys as variables
envFrom[].prefixa 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 isMain fields
configMapConfigMap keys as filesname, items: [{key, path}] — pick keys and file names, defaultMode — file permissions (default 0644), optional
secretSecret keys as files (decoded)secretName (not name!), items, defaultMode
emptyDiran empty directory for the lifetime of the pod; shared by its containersmedium: Memory — in RAM (tmpfs), sizeLimit: 100Mi
persistentVolumeClaima persistent disk via a PVCclaimName, readOnly
hostPatha directory or file on the nodepath, type: Directory | DirectoryOrCreate | File | FileOrCreate | Socket
projectedseveral sources (configMap, secret, downwardAPI, token) in one directorysources: […]
downwardAPIlabels, annotations, pod name as filesitems: [{path, fieldRef}]

volumeMounts[] fields:

FieldMeaningDefault / notes
namevolume name from volumesrequired
mountPathwhere to mount in the containerrequired; hides whatever was in that image directory
subPathmount only one file/subdirectory of the volumethe image directory's contents aren't hidden, but the file is not updated when the ConfigMap/Secret changes
readOnlyread-onlyfalse (configMap and secret are read-only anyway)

PersistentVolumeClaim

FieldMeaningDefault / notes
spec.accessModesReadWriteOnce (RWO) — write from one node; ReadOnlyMany (ROX); ReadWriteMany (RWX) — write from many nodes; ReadWriteOncePod — a single pod onlyrequired in practice; not all storage supports RWX
spec.resources.requests.storagesize: 1Gi, 500Mi
spec.storageClassNamestorage class (standard, gp3, …)omitted — the default class; "" — no dynamic provisioning
spec.volumeModeFilesystem / BlockFilesystem

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 -d reads 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' | base64 without -n also encodes the newline: the password gets an extra \n, and logging in "inexplicably" fails.
  • A Secret's data holds only base64. The API server rejects a plain-text value in data (illegal base64 data), while kubeconform lets it through. For plain text there's stringData.
  • defaultMode file permissions are octal. kubectl reads 0400 as an octal number (256), while YAML 1.2 tools read it as decimal 400: yq -o json turns it into 400, i.e. different permissions. In JSON manifests write the decimal value: 256 for 0400, 420 for 0644.
  • Numbers and booleans in a ConfigMap's data must be quoted: PORT: "8080", DEBUG: "true". Without quotes kubeconform returns expected 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.
  • mountPath on an existing directory hides everything the image had there. Mount a ConfigMap at /etc/nginx and the image's nginx.conf is gone. For a single file use subPath.
  • secretName, not name. For a configMap volume the field is called name, for a secret volume it's secretName. Mix them up and the schema replies additionalProperties 'name' not allowed.
  • --from-env-file can't be combined with --from-literal and --from-file in one kubectl create configmap command.
  • ConfigMap or Secret not created yet — the pod won't start (CreateContainerConfigError) until the object appears. If the object is optional, set optional: true.
  • hostPath ties the pod to a node and gives access to its filesystem. A pod on another node sees different data; in shared clusters hostPath is often forbidden by policy.
  • emptyDir lives as long as the pod. A container restart keeps the data, but recreating the pod (a rollout, moving to another node) wipes it.
  • A ReadWriteOnce PVC and several Deployment replicas — a second pod on another node can't attach the disk and hangs in ContainerCreating. A StatefulSet gives each replica its own disk.

See also

kubectl · kubeconform · yq · base64 · openssl · env · k8s-workloads · k8s-networking · k8s-rbac