Configuration, secrets, storage and access · 6 MIN READ

ConfigMaps: settings for pods through env, envFrom and mounted files

Store non-secret settings in a ConfigMap, consume them as environment variables or files, diagnose a missing ConfigMap or key, and roll pods so that they pick up a change.

A container image should be the same artifact in every environment; what differs between staging and production is configuration. A ConfigMap keeps that configuration in the cluster as key-value pairs that pods read as environment variables or as files. How a pod reads it decides what happens when the ConfigMap is missing and when it changes.

kubernetes · A MAP OF THE IDEA

  1. Create the ConfigMap
  2. Reference it via env or volume
  3. Validate config at startup
  4. Roll pods when it changes

Useful when

  • One image runs in every environment with different settings.
  • Mounted files refresh in place without restarting pods.

Watch out

  • Environment variables never change in a running container.
  • A missing ConfigMap or key blocks the container from starting.

Implementation & operation cost: One more object per service, plus a deliberate rollout or a hashed name whenever its content changes.

01

What a ConfigMap holds

A ConfigMap is a namespaced object with a data map of UTF-8 strings and an optional binaryData map for base64-encoded bytes. Keys may contain letters, digits, dashes, underscores and dots, so a key can be a variable name such as LOG_LEVEL or a file name such as app.yaml whose value is a whole file. The object is stored in etcd and limited to 1 MiB, and a pod can only reference ConfigMaps in its own namespace. ConfigMaps are not for credentials: anyone who can read the object sees every value, which is what Secrets are for. kubectl create configmap builds one from --from-literal, --from-file or --from-env-file; in Git you keep the manifest.

yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: api-config
data:
  DATABASE_URL: postgres://app@db:5432/app
  LOG_LEVEL: info
  app.yaml: |
    listen: :8080
    features:
      search: true
Read the code

Two keys hold single values meant for environment variables. The app.yaml key uses a YAML block scalar (|), so its value is a multi-line file that a volume mount can turn into /etc/api/app.yaml. Nothing in the object says how it will be consumed; each pod that references it decides that.

02

Three ways to consume it

env with valueFrom.configMapKeyRef sets one variable from one key and lets you choose its name. envFrom imports every key of a ConfigMap as a variable, optionally with a prefix; it is convenient, but it hides which variables a container depends on, and a key someone adds later appears at the next container start without review. A configMap volume writes each key as a file under the mount path, or only the keys listed in items. Both env forms are resolved by the kubelet once, when the container is created. Mounted files behave differently: after the ConfigMap changes, the kubelet refreshes them in place, typically within a minute, by swapping a symlink so readers never see half a file. Files mounted with subPath are never refreshed.

yaml
apiVersion: v1
kind: Pod
metadata:
  name: api
spec:
  containers:
  - name: api
    image: gopherforge/api:v1
    env:
    - name: DATABASE_URL
      valueFrom:
        configMapKeyRef:
          name: api-config
          key: DATABASE_URL
    envFrom:
    - configMapRef:
        name: api-flags
        optional: true
    volumeMounts:
    - name: config
      mountPath: /etc/api
      readOnly: true
  volumes:
  - name: config
    configMap:
      name: api-config
      items:
      - key: app.yaml
        path: app.yaml
Read the code

DATABASE_URL comes from one named key of api-config. envFrom adds every key of a second ConfigMap, api-flags, and optional: true lets the container start even when that ConfigMap does not exist. The volume projects only the app.yaml key, as the read-only file /etc/api/app.yaml; without items, every key would become a file in that directory.

03

When the ConfigMap or a key is missing

A pod is scheduled even if a ConfigMap it references does not exist; the failure appears on the node. For env and envFrom the kubelet cannot build the environment, so the container is never started: kubectl get pods shows CreateContainerConfigError, and the events say Error: configmap "api-config" not found, or couldn't find key DATABASE_URL in ConfigMap default/api-config when only the key is missing. For a volume the pod stays in ContainerCreating with FailedMount events such as MountVolume.SetUp failed for volume "config" : configmap "api-files" not found. Both recover on their own once the ConfigMap or key appears, because the kubelet keeps retrying. Mark a reference optional: true only when the application has a sensible default without it.

04

Changes need a rollout; immutable ConfigMaps make that explicit

Because environment variables are fixed when the container is created, editing a ConfigMap changes nothing in running pods that read it through env. kubectl rollout restart deploy/api writes a kubectl.kubernetes.io/restartedAt annotation into the pod template, and that template change makes the Deployment roll out new pods, which read the current values. Many teams make the change explicit instead: Kustomize's configMapGenerator appends a hash of the content to the name, so new content means a new name, a changed pod template and an ordinary rollout that can also be rolled back. Setting immutable: true goes further. The API server rejects any change to its data, so a new version is a new object, and the kubelet stops watching it, which reduces API server load in large clusters.

yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: api-config-7d4f9c
immutable: true
data:
  DATABASE_URL: postgres://app@db:5432/app
  LOG_LEVEL: info
Read the code

The suffix stands for a content hash, so the next version is another object rather than an edit. Pods keep the old values until their template points at the new name, and nothing can change an immutable ConfigMap underneath running pods. Delete an old version only when no ReplicaSet you might roll back to still references it.

05

Twelve-factor configuration in a Go service

The twelve-factor rule is to read configuration from the environment and treat it as input that is validated at startup. A Go service should gather everything it needs into one struct, apply defaults only where a default is genuinely safe, and exit with a clear message when a required value is missing. Failing at startup is useful: Kubernetes shows it as CrashLoopBackOff with the reason in kubectl logs, and a rolling update with a broken configuration stalls because the new pods never become ready, while the old pods keep serving. Files from a ConfigMap volume suit structured configuration that is too large for variables; read them at startup and, if you reload them, watch the directory rather than the file because of the symlink swap.

go
type Config struct {
	DatabaseURL string
	LogLevel    slog.Level
	Addr        string
}

func LoadConfig() (Config, error) {
	cfg := Config{LogLevel: slog.LevelInfo, Addr: ":8080"}
	cfg.DatabaseURL = os.Getenv("DATABASE_URL")
	if cfg.DatabaseURL == "" {
		return cfg, errors.New("DATABASE_URL is required (set it from a ConfigMap or Secret)")
	}
	if v, ok := os.LookupEnv("LOG_LEVEL"); ok {
		if err := cfg.LogLevel.UnmarshalText([]byte(v)); err != nil {
			return cfg, fmt.Errorf("LOG_LEVEL: %w", err)
		}
	}
	if v := os.Getenv("ADDR"); v != "" {
		cfg.Addr = v
	}
	return cfg, nil
}
Read the code

DATABASE_URL has no safe default, so its absence is an error, worded like the message the lab image prints. LOG_LEVEL is optional but must parse: slog.Level accepts names such as info and debug, and a typo fails startup instead of silently logging at the wrong level. main calls LoadConfig once, logs the error and exits with a non-zero status.

06

Try it in the lab terminal

Run gopherforge/api:v1 without any configuration and watch it crash, then give it a ConfigMap and confirm the variables inside the container. Finally change LOG_LEVEL and roll the Deployment so that the new value reaches the pods. cluster tick 20s advances the lab clock so the crash loop has time to show; on a real cluster you would simply wait. Read the log before fixing anything: the message names the missing variable.

bash
kind create cluster
kubectl create deployment api --image=gopherforge/api:v1
cluster tick 20s
kubectl get pods
kubectl logs deploy/api
kubectl create configmap api-config --from-literal=DATABASE_URL=postgres://app@db:5432/app --from-literal=LOG_LEVEL=info
kubectl set env deploy/api --from=configmap/api-config
kubectl rollout status deploy/api
kubectl exec deploy/api -- env
kubectl logs deploy/api
kubectl create configmap api-config --from-literal=DATABASE_URL=postgres://app@db:5432/app --from-literal=LOG_LEVEL=debug --dry-run=client -o yaml | kubectl apply -f -
kubectl rollout restart deploy/api
kubectl rollout status deploy/api
kubectl exec deploy/api -- printenv LOG_LEVEL
Read the code

After 20 seconds api-<hash>-<id> is in CrashLoopBackOff with 2 restarts, and the log says err="DATABASE_URL is required (set it from a ConfigMap or Secret)". set env --from=configmap/api-config changes the pod template, so a new pod rolls out; exec env lists DATABASE_URL and LOG_LEVEL=info, and the log now shows msg="connected". The dry-run pipe into kubectl apply is a repeatable way to edit a ConfigMap (a real cluster also warns once that the object lacked apply's annotation). The running pod keeps info until rollout restart replaces it; printenv in the new pod prints debug.

TAKE THIS WITH YOU

ConfigMaps carry non-secret settings into pods as variables or files; env values are fixed when a container starts, so a change needs a rollout, while mounted files refresh in place. A missing ConfigMap or key holds the container in CreateContainerConfigError or FailedMount until it appears.

Check your understanding

You change LOG_LEVEL in the ConfigMap that a Deployment reads through env valueFrom. An hour later its pods still log at info. What makes them use the new value?

Go to the source

Progress stays in this browser. No account needed.